Skip to content

Instantly share code, notes, and snippets.

@jondkinney
Forked from mikeweber/placeholder_behavior.js
Created April 13, 2010 05:47
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 jondkinney/364351 to your computer and use it in GitHub Desktop.
Save jondkinney/364351 to your computer and use it in GitHub Desktop.
Placeholder swap
// To get this code to work, simply add a placeholder attribute to any of your inputs.
// This code requires no-conflict jQuery (var $j = jQuery.noConflict();) and Modernizr.
// Also you should add something similar to the following to your stylesheets.
//
// .placeholder{
// color: #666;
// }
jQuery.fn.set_placeholder = function() {
if ($j(this).attr('placeholder') && ($j(this).val() == '' || $j(this).val() == $j(this).attr('placeholder'))) {
$j(this).addClass('placeholder');
$j(this).val($j(this).attr('placeholder'));
} else {
$j(this).removeClass('placeholder');
}
}
jQuery.fn.clear_placeholder = function() {
$j(this).removeClass('placeholder');
if ($j(this).val() == $j(this).attr('placeholder')) {
$j(this).val('');
}
}
var placeholder_behavior = Behavior.create(
{
initialize: function(event) { $j(this.element).set_placeholder() },
onblur: function(event) { $j(this.element).set_placeholder() },
onfocus: function(event) { $j(this.element).clear_placeholder() }
}
);
if (!Modernizr.input.placeholder) {
Event.addBehavior({
'[placeholder]' : placeholder_behavior,
'form:submit' : function() { $j('.placeholder').clear_placeholder() }
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment