home / blog

Assorted IE8 polyfills: forEach, trim, placeholders

I ended up using all of the following during recent development of weathersupermarket 2.0 and another site.

Array.prototype.forEach() implemented using a for loop and fn.apply

  if (typeof Array.prototype.forEach !== 'function') {
    Array.prototype.forEach = function(callback, context) {
      for (var i = 0; i < this.length; i++) {
        callback.apply(context, [ this[i], i, this ]);
      }
    };
  }

String.prototype.trim() implemented using a regex. Just replace leading a trailing spaces with the empty string.

  if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
  }

The input/textarea placeholder attribute implemented using jQuery and data- attributes. Custom data attributes are only standardized in HTML5 but pretty much every browser ever has supported them via DOM setAttribute() which jQuery attr() delegates onto.

  if (!Modernizr.input.placeholder) {
    var addPlaceholder = function() {
      var input = $(this);
      if (input.val() == '' || input.val() === input.attr('placeholder')) {
        input.addClass('placeholder');
        setValue(input, input.attr('placeholder'));
      }
    };
    $('input[placeholder],textarea[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() === input.attr('placeholder')) {
        setValue(input, '');
        input.removeClass('placeholder');
      }
    }).blur(addPlaceholder);
    $('input[placeholder],textarea[placeholder]').each(function(it) {
      addPlaceholder.apply(this);
    });

  }

JSON support for IE8. I actually found this was only necessary when I needed to do raw JSON.stringify() calls etc. jQuery $.ajax is coded to use a regex/eval solution if the JSON native object does not exist. So I only included the Douglas Crockford json2.js on one of the sites in question.

This entry was posted in geek and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.