Last active
December 14, 2015 01:19
-
-
Save Nek-/5005132 to your computer and use it in GitHub Desktop.
Placeholder inputs easily with mootools.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Mootools Placeholder Class. | |
* | |
* @author Nek <[email protected]> | |
* @company Wandi | |
* | |
* Set this data (via store) on elements: | |
* - "placeholder-text": The text of the placeholder | |
* | |
* Use a class to detect if the current text is a placeholder. | |
* The goal is to be able to change the css form. | |
* The default class is "active-placeholder" | |
* | |
* You can pass some options. See first line of initialize method. | |
* | |
* Notice: For HTML5 use, you should prefer to use the "placeholder" attribute. | |
* | |
* ------------------------ | |
* Example of use: | |
* new MootoolsPlaceholder({ | |
* 'class': 'my_placeholder', | |
* 'active-class': 'my_placeholder_is_active', | |
* 'container': $('id_of_my_element') | |
* }); | |
* .my_placeholder_is_active { | |
* color: gray; | |
* } | |
* | |
*/ | |
var MootoolsPlaceholder = new Class({ | |
/** | |
* Init the class | |
* & call the build | |
*/ | |
initialize: function(options){ | |
this.options = { | |
'class': 'has-placeholder', | |
'active-class': 'active-placeholder', | |
'container': document | |
}; | |
if (options) | |
this.options = Object.merge(this.options, options); // copy options | |
this.build(); | |
}, | |
/** | |
* Make concerned elements placeholdered! | |
* use the "class" of the option tab | |
* | |
* | |
* @return void | |
* @see unfocus & focus to see methods call on this events | |
*/ | |
build: function() { | |
this.options.container | |
.getElements('.' + this.options['class']) | |
.each((function(el) { | |
el.store('placeholder-text', el.get('value')); | |
el.addClass(this.options['active-class']); | |
el.addEvent('focus', this.focus.bind(this)); | |
el.addEvent('blur', this.unfocus.bind(this)); | |
}).bind(this)); | |
}, | |
/** | |
* Called on blur, change the text of the element | |
* only when this one is empty | |
* | |
* @return void | |
*/ | |
unfocus: function(e) { | |
var el = e.target; | |
if (el.get('value') == '') { | |
el.set('value', el.retrieve('placeholder-text')); | |
el.addClass(this.options['active-class'], 0); | |
} | |
}, | |
/** | |
* Called on focus, change the text of the element | |
* only if the text is under placeholder (activeplaceholder) | |
*/ | |
focus: function(e) { | |
var el = e.target; | |
if (el.hasClass(this.options['active-class'])) { | |
el.set('value', ''); | |
el.removeClass(this.options['active-class']); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment