Skip to content

Instantly share code, notes, and snippets.

@fcurella
Created January 15, 2011 21:44
Show Gist options
  • Save fcurella/781289 to your computer and use it in GitHub Desktop.
Save fcurella/781289 to your computer and use it in GitHub Desktop.
Add 'placeholder' attribute support to inputs and textareas. Requires jQuery and Modernizr.
$(function(){
if (!Modernizr.input.placeholder) {
$('input[placeholder], textarea[placeholder]').each(function(index, elem) {
elem = $(elem);
placeholder = elem.attr('placeholder');
elem_id = elem.attr('id');
elem_name = elem.attr('name');
clone = elem.clone();
clone.hide();
if (elem_id) {
clone.attr({'id': elem_id+'-fake'});
}
if (elem_name) {
clone.attr({'name': elem_name+'-fake'});
}
clone.addClass('fake');
clone.data({'original': $(elem)});
clone.val(placeholder);
clone.focus(function(e) {
e.preventDefault();
$(this).hide();
$(this).data('original').show().focus();
});
elem.blur(function() {
if ($(this).val() == '') {
$(this).hide();
$(this).next().show();
}
});
elem.after(clone);
elem.blur();
});
}
});
@jsdev
Copy link

jsdev commented May 28, 2013

to be safe I'd use: $(e.currentTarget) versus $(this) and I'd chain it if not caching the jquery object.. [you cached elem and clone]

$(e.currentTarget)
.hide()
.data('original')
.show().focus();

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