Created
February 1, 2011 03:10
-
-
Save balupton/805359 to your computer and use it in GitHub Desktop.
Set or Fetch a HTML5 Placeholder without backwards compatibility for older browsers
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
/** | |
* 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires modernizr:
http://www.modernizr.com/