Skip to content

Instantly share code, notes, and snippets.

@rudiedirkx
Last active October 8, 2015 15:18
Show Gist options
  • Save rudiedirkx/3351144 to your computer and use it in GitHub Desktop.
Save rudiedirkx/3351144 to your computer and use it in GitHub Desktop.
Placeholder polyfill (Drupal behavior)
// As seen in bozo/custom.js
(function($) {
Drupal.behaviors.placeholderPolyfill = {
attach: function(context, settings) {
if ( !('placeholder' in document.createElement('input')) ) {
var onFocus = function(e) {
this.$this || (this.$this = $(this));
if ( this.value == this.$this.attr('placeholder') ) {
this.value = '';
this.$this.removeClass('showing-placeholder');
}
};
var onBlur = function(e) {
this.$this || (this.$this = $(this));
if ( this.value == '' ) {
this.value = this.$this.attr('placeholder');
this.$this.addClass('showing-placeholder');
}
};
var formClearPlaceholders = function(placeholdered) {
$.each(placeholdered, function(i, el) {
onFocus.call(el);
});
// @TODO Is there a better way to be the very last?
setTimeout(function() {
$.each(placeholdered, function(i, el) {
onBlur.call(el);
});
}, 50);
};
// Find all placeholder elements and attach events
$('input[placeholder], textarea[placeholder]')
.bind('focus', onFocus)
.bind('blur', onBlur)
.each(function(i, el) {
onBlur.call(el);
// Has form and form wasn't placeholdered yet.
if ( el.form && !el.form.$placeholdered ) {
el.form.$placeholdered = [el];
var $form = $(el.form);
var submitId = $form.find('.form-submit').attr('id');
if (Drupal.ajax && Drupal.ajax[submitId]) {
var ajax = Drupal.ajax[submitId];
ajax.options.beforeSerialize = function(element_settings, options) {
formClearPlaceholders(ajax.element.form.$placeholdered);
return ajax.beforeSerialize(element_settings, options);
};
}
// Remove placeholders on submit.
$form.bind('submit', function(e) {
formClearPlaceholders(this.$placeholdered);
});
// Move new submit to the start.
var listeners = $form.data('events').submit;
listeners.unshift(listeners.pop());
}
// Has form, so add to placeholdered stack.
else if ( el.form ) {
el.form.$placeholdered.push(el);
}
});
}
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment