Skip to content

Instantly share code, notes, and snippets.

@balupton
Created February 1, 2011 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balupton/805359 to your computer and use it in GitHub Desktop.
Save balupton/805359 to your computer and use it in GitHub Desktop.
Set or Fetch a HTML5 Placeholder without backwards compatibility for older browsers
/**
* Set or Fetch a HTML5 Placeholder
* without backwards compatibility for older browsers
* @author Benjamin Arthur Lupton
* @license Public Domain
*/
$.fn.placeholder = $.fn.placeholder||function(placeholder) {
// Prepare
var $input = $(this);
// Check
if ( typeof placeholder === 'undefined' ) {
return $input.attr('placeholder')||$input.attr('title');
}
// Config
var
config = {
hasClass: 'sparkle-hint-has',
hintedClass: 'sparkle-hint-hinted',
};
// Events
var events = {
focusEvent: function(){
var $input = $(this);
var tip = $input.placeholder();
var val = $input.val();
// Handle
if (tip === val) {
$input.val('').removeClass(config.hintedClass);
}
// Done
return true;
},
blurEvent: function(){
var $input = $(this);
var tip = $input.placeholder();
var val = $input.val();
// Handle
if (tip === val || !val) {
$input.val('').addClass(config.hintedClass).val(tip);
}
// Done
return true;
},
submitEvent: function(){
$(this).find('input.'+config.hasClass).trigger('focus');
}
};
// Apply
if ( typeof Modernizr !== 'undefined' && Modernizr.input.placeholder ) {
// We Support HTML5 Hinting
// Set the placeholder as the title if the placeholder does not exist
// We could use a filter selector, however we believe this should be faster - not benchmarked though
$input.attr('title',placeholder).attr('placeholder',placeholder);
}
else {
// We Support Javascript Hinting
$input.attr('title',placeholder).attr('placeholder',placeholder);
$input.once('focus',events.focusEvent).once('blur',events.blurEvent).trigger('blur');
$input.parents('form').once('submit',events.submitEvent);
}
// Chain
return $input;
};
@balupton
Copy link
Author

balupton commented Feb 1, 2011

Requires modernizr:
http://www.modernizr.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment