Skip to content

Instantly share code, notes, and snippets.

@chriscoyier
Created March 10, 2011 14:57
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 chriscoyier/864210 to your computer and use it in GitHub Desktop.
Save chriscoyier/864210 to your computer and use it in GitHub Desktop.
$(function() {
var $el;
$("input[placeholder]").each(function() {
$el = $(this);
$el
.css("color", "#ccc")
.val($el.attr("placeholder"))
.data("orig-text", $el.val())
// knows data here
$el
.focus(function() {
$el = $(this);
// undefined data here
if ($el.val() == $el.data("orig-text")) {
alert("it's the same");
$el.val("");
$el.css("color", "black");
}
})
.blur(function() {
$el = $(this);
if ($el.val() == "") {
$el.val($el.data("orig-text"));
$el.css("color", "#ccc");
}
});
});
});
@Mottie
Copy link

Mottie commented Mar 10, 2011

You might want to check if the browser supports HTML5 placeholder ;)

 if (typeof(document.createElement('input').placeholder) === 'undefined') {
   // not supported, so add functionality
 }

@chriscoyier
Copy link
Author

The point of this was to include as a script after you've checked for support with Modernizr (as part of a larger demo). I thought at first it was because I was using jQuery 1.4.4 and that .data() didn't work in the same way, but that didn't turn out to be the case. Still confusing.

@Mottie
Copy link

Mottie commented Mar 10, 2011

I can't test it since IE9 doesn't seem to have a problem, but I seem to remember the problem is older IE versions don't like dashes in the data name.

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