Skip to content

Instantly share code, notes, and snippets.

@garyharan
Created May 20, 2011 14: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 garyharan/983059 to your computer and use it in GitHub Desktop.
Save garyharan/983059 to your computer and use it in GitHub Desktop.
Make older browsers act as do modern browsers in regards to placeholder in inputs
$(function(){
if ("placeholder" in document.createElement( "input" )){ return }
$('input[placeholder]').each(function(){
$(this).val($(this).attr('placeholder')).css('color', '#999')
}).focus(function(){
var placeholder = $(this).attr('placeholder')
$(this).val( placeholder == $(this).val() || $(this).val() == '' ? '' : $(this).val() ).css('color', '#333')
}).blur(function(){
var placeholder = $(this).attr('placeholder')
if ($(this).val() == '') {
$(this).val(placeholder).css('color', '#999')
}
});
})(jQuery);
@cloudhead
Copy link

Same thing in vanilla javascript!

(function () {
    var inputs = document.getElementsByTagName('input');
    var text, e;

    for (var i = 0; i < inputs.length; i ++) {
        e = inputs[i];
        if (text = e.value = e.getAttribute('placeholder')) {
            e.style.color = '#999';

            e.onfocus = function () {
                if (e.value === text) {
                    e.value = '';
                    e.style.color = '#333';
                }
            };
            e.onblur = function () {
                if (! e.value.trim()) {
                    e.value = text;
                    e.style.color = '#999';
                }
            };
        }
    }
})();

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