jQuery: emulating the placeholder attribute

Internet Explorer 8 doesn't support the HTML5 placeholder attribute that we can use to label our text fields. Fortunately, we can emulate this attribute with jQuery. Let's see how.

We have to create a plugin to exactly position an element with its text label just over a text field:

(function($) {

 $.fn.placeholder = function(options) {
 
  var that = this;
  
  if(!that.is('input[type=text]')) {
  
   return;
  
  }
  
  var defaults = {
  
   text: 'Placeholder'
  
  };
  
  options = $.extend(defaults, options);
  
  var top = that.offset().top;
  var left = that.offset().left;
  
  return that.each(function() {
  
   $('<span class="placeholder"/>').text(options.text).
   css({
    position: 'absolute',
    top: top,
    left: left
   }).insertAfter(that);
   
   that.focus(function() {
   
   
    that.next('span.placeholder').hide();
   
   });
   
   that.blur(function() {
   
    if(that.val() == '') {
    
     that.next('span.placeholder').show();
    
    }
   
   }); 
  
  });
 
 };

})(jQuery);

We use the top and left offsets of the text field to position our element. We use then focus and blur to hide the placeholder while a user is typing and to show it again if the field's value is empty, respectively.

An example:

$(function() {

 $('#text', '#form').placeholder({text: 'Lorem'});
 $('#text2', '#form').placeholder({text: 'Lorem ipsum'});

});

You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.