Resources: jQuery / Javascript

Text field placeholder text cross-browser

27 September 2012

In a recent project I have struggled to deal with Microsoft’s “Brand New” Internet Explorer 9′s “support” for HTML5 and CSS3. IE9 support for HTML5 and CSS3 is laughable with many, many holes and incompatibilities. One in particular that I’m dealing with is an input field’s placeholder attribute. As I include jQuery in 80% of my projects, I turned to jQuery for a solution, and alas! jQuery pulls through again. Just drop in this code in your JavaScript and you don’t even need to make any changes to your CSS or HTML!

    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();

Tags: , ,

Let's work together