Simple script for creating cross browser input placeholders

-

Introduction

When building HTML forms, most browsers support the placeholder attribute:

<input type="text" placeholder="Freelance JavaScript Developer">

but this does not always work in the older browsers therefore you have to dynamically add and remove the value of the input attribute using the blur and focus JavaScript events.

Example Usage

The HTML:

<form>
  <input type="text" data-placeholder="Freelance"  />
  <input type="text" data-placeholder="JavaScript" />
  <input type="text" data-placeholder="Developer"  />
</form>

If you want to apply this to all input text boxes globally you can just use some inline JavaScript. First you get all the input text boxes:

var textInputs = $(‘body’).find([data-placeholder]);

Then you loop over each input text box and apply the Blur and Focus event listeners:

textInputs.each(function() {
  var placeholderVal = $(this).data(‘placeholder’);
  if(typeof placeholderVal !== ‘undefined’) {
    $(this).blur(function() {
      if($(this).val() ==) {
        $(this).val(placeholderVal);
      }
    });
  }
});
textInputs.each(function() {
  var placeholderVal = $(this).data(‘placeholder’);
  if(typeof placeholderVal !== ‘undefined’) {
    $(this).focus(function() {
      if($(this).val() == placeholderVal) {
        $(this).val();
      }
    });
  }
});
 

Or you can use JavaScript prototypes, this example also allows you to add a data attribute (data-placeholder) to your input elements and then parse the parent element (this could be the the form element for example).

function Placeholders(data) {
  this.textInputs = data.element.find([data-placeholder]);
  this.blur();
  this.focus();
  this.set();
}
Placeholders.prototype.blur = function() {
  this.textInputs.each(function() {
    var placeholderVal = $(this).data(‘placeholder’);
    if(typeof placeholderVal !== ‘undefined’) {
      $(this).blur(function() {
        if($(this).val() ==) {
          $(this).val(placeholderVal);
        }
      });
    }
  });
}
Placeholders.prototype.focus = function() {
  this.textInputs.each(function() {
    var placeholderVal = $(this).data(‘placeholder’);
    if(typeof placeholderVal !== ‘undefined’) {
      $(this).focus(function() {
        if($(this).val() == placeholderVal) {
          $(this).val();
        }
      });
    }
  });
}
Placeholders.prototype.set = function() {
  this.textInputs.each(function() {
    var placeholderVal = $(this).data(‘placeholder’);
    if(typeof placeholderVal !== ‘undefined’) {
      $(this).val(placeholderVal);
    }
  });
}
new Placeholders({ element: $(‘form’) });

Your comments.