Created
December 28, 2010 03:28
-
-
Save mattfarina/756870 to your computer and use it in GitHub Desktop.
Drupal / jQuery html5 placeholder support for browsers without native support
This file contains 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
// Here we use a similar set of variables passed in as jQuery. The lone difference is | |
// the inclusion of the Drupal variable. We pass in the global variables we use which | |
// provides proper dependency injection and for compressors to have names that can be | |
// more easily shrunk. | |
(function($, Drupal, window, document, undefined) { | |
Drupal.sitetheme = Drupal.sitetheme || {}; | |
/* | |
* Initialize placeholder functionality on a text based input element. | |
* this in the function is the DOM Element. | |
*/ | |
Drupal.sitetheme.initPlaceholder = function() { | |
var element = $(this), | |
text = element.attr('placeholder'), | |
addPlaceholder = function() { | |
if (!element.val() || element.val() === text) { | |
element.val(text).addClass('placeholder-text'); | |
} | |
}, | |
removePlaceholder = function() { | |
if (element.val() === text) { | |
element.val('').removeClass('placeholder-text'); | |
} | |
}; | |
addPlaceholder(); | |
element.focus(removePlaceholder) | |
.blur(addPlaceholder); | |
element.closest('form').submit(removePlaceholder) | |
.bind('reset', function() { | |
// When the reset event fires the form reset has not actually | |
// happened. We use a timeout so we can add the placeholder | |
// after the reset happens. | |
setTimeout(addPlaceholder, 50); | |
}); | |
}; | |
/* | |
* Make placeholder function in browsers that do not naticely support it. | |
*/ | |
Drupal.behaviors.sitetheme = { | |
attach: function(context, settings) { | |
// Detect placeholder support. | |
var supported = 'placeholder' in document.createElement('input'); | |
if (supported || !$(context).find(':input[placeholder]').length) { | |
// If the browser natively supports placeholder or it is not used in | |
// a page return as there is nothing to do. | |
return; | |
} | |
// jQuery internally converts $(selector, context) into $(context).find(selector) | |
// for cases where context is a DOM Element. Doing so natively does less logic | |
// which includes avoiding a regex. | |
$(context).find(':input[placeholder]').each(Drupal.sitetheme.initPlaceholder); | |
} | |
}; | |
// We pass in any global variables we use. Dependency injection FTW. | |
})(jQuery, Drupal, this, this.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment