HTML5 placeholder disappears on focus

Stefano labels

Stefano J. Attardi wrote a nice jQuery plugin that just does that.
It is more stable than Robert’s and also fades to a lighter grey when the field gets focused.

  • See the demo page
  • Grab it on GitHub
  • Play with the fiddle

I modified his plugin to read placeholder attribute as opposed to manually creating a span.
This fiddle has complete code:

HTML

<input type="text" placeholder="Hello, world!">

JS

// Original code by Stefano J. Attardi, MIT license

(function($) {
    function toggleLabel() {
        var input = $(this);

        if (!input.parent().hasClass('placeholder')) {
            var label = $('<label>').addClass('placeholder');
            input.wrap(label);

            var span = $('<span>');
            span.text(input.attr('placeholder'))
            input.removeAttr('placeholder');
            span.insertBefore(input);
        }

        setTimeout(function() {
            var def = input.attr('title');
            if (!input.val() || (input.val() == def)) {
                input.prev('span').css('visibility', '');
                if (def) {
                    var dummy = $('<label></label>').text(def).css('visibility','hidden').appendTo('body');
                    input.prev('span').css('margin-left', dummy.width() + 3 + 'px');
                    dummy.remove();
                }
            } else {
                input.prev('span').css('visibility', 'hidden');
            }
        }, 0);
    };

    function resetField() {
        var def = $(this).attr('title');
        if (!$(this).val() || ($(this).val() == def)) {
            $(this).val(def);
            $(this).prev('span').css('visibility', '');
        }
    };

    var fields = $('input, textarea');

    fields.live('mouseup', toggleLabel); // needed for IE reset icon [X]
    fields.live('keydown', toggleLabel);
    fields.live('paste', toggleLabel);
    fields.live('focusin', function() {
        $(this).prev('span').css('color', '#ccc');
    });
    fields.live('focusout', function() {
        $(this).prev('span').css('color', '#999');
    });

    $(function() {
       $('input[placeholder], textarea[placeholder]').each(
           function() { toggleLabel.call(this); }
       );
    });

})(jQuery);

CSS

.placeholder {
  background: white;
  float: left;
  clear: both;
}
.placeholder span {
  position: absolute;
  padding: 5px;
  margin-left: 3px;
  color: #999;
}
.placeholder input, .placeholder textarea {
  position: relative;
  margin: 0;
  border-width: 1px;
  padding: 6px;
  background: transparent;
  font: inherit;
}

/* Hack to remove Safari's extra padding. Remove if you don't care about pixel-perfection. */
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .placeholder input, .placeholder textarea { padding: 4px; }
}

Leave a Comment