Skip to content

Instantly share code, notes, and snippets.

@b-ma
Created May 7, 2014 09:35
Show Gist options
  • Save b-ma/e2f67f54a3690d3e2213 to your computer and use it in GitHub Desktop.
Save b-ma/e2f67f54a3690d3e2213 to your computer and use it in GitHub Desktop.
jquery AMD placeholder plugin
define([
'jquery'
], function($) {
'use strict';
// extends $.support
// http://stackoverflow.com/questions/3937818/how-to-test-if-the-browser-supports-the-native-placeholder-attribute
$.support.placeholder = (function() {
var input = document.createElement( 'input' );
return 'placeholder' in input;
}());
// placeholder fallback
(function($, undefined) {
var pluginName = 'placeholder';
var Plugin = function($el) {
this.$el = $el;
if (!this.$el.attr('placeholder')) { return; }
this.$el.data('placeholder', this.$el.attr('placeholder'));
this.$el.attr('value', this.$el.data('placeholder'));
console.log(this.$el.attr('value'));
this.$el.on({
focus: $.proxy(function() {
if (this.$el.attr('value') === this.$el.data( 'placeholder' )) {
this.$el.attr('value', '');
}
}, this),
blur: $.proxy(function() {
if (this.$el.attr('value') === '') {
this.$el.attr('value', this.$el.data('placeholder'));
}
}, this)
});
};
$.fn[pluginName] = function(options) {
var $elms = $(this);
if ($.support.placeholder) {
return $elms;
}
return $.each($elms, function(index, el) {
var $el = $(el);
if (!$.data($el, 'plugin-' + pluginName)) {
$.data($el, 'plugin-' + pluginName, new Plugin($el));
}
});
}
}($));
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment