IE8 support chapter 1

Internet Explorer 8 is still widly used in the industry and makes sometimes developing a web application pretty hard. Here’s some things I learned when I had to deal with this version of IE:

indexOf

This snippet returns the index within the first occurrence of the specified value.

function indexOf(arr, obj){
  if (arr.indexOf) return arr.indexOf(obj);
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] === obj) return i;
  }
  return -1;
};

trim

This method returns the string stripped of whitespace from both ends.

function trim(str){
  if(str.trim) return str.trim();
  return str.replace(/^\s*|\s*$/g, '');
};

events

Listen an event on IE8 is quite different from the other browsers:

var attach = window.addEventListener ? 'addEventListener' : 'attachEvent',
    detach = window.removeEventListener ? 'removeEventListener' : 'detachEvent',
    prefix = attach !== 'addEventListener' ? 'on' : '';

function bind(el, type, fn, capture){
  el[attach](prefix + type, fn, capture || false);
  return fn;
};

function unbind(el, type, fn, capture){
  el[detach](prefix + type, fn, capture || false);
  return fn;
};

Reserved keywords

IE8 doesn’t joke around with JavaScript reserved keywords. When some other browsers are permisive, these keywords can’t be used with IE8.

Here’s a list of reserved keywords.

Query Selection

How to query select a fragment of a document? Too many times I see this kind of answer:

//you should use jQuery
$('.list li.pair');

jQuery is great but I don’t see the point to use it just to select an element. IE8 supports really well querySelector and querySelectorAll.

//you should use jQuery
document.querySelectorAll('.list li.pair');

Adjacent Element/HTML

We often criticize IE8 but I feel like there is not so much to do to support it (at least to make a MVC library). Moreover, there is some cool stuff that IE8 support since a long time, one of them is insertAdjacentHTML and insertAdjacentElement.

These methods allows you to insert a DOM Element in a document with more control than appendChild. Here’s an example:

var list = document.querySelector('.list');
list.insertAdjacentHTML('beforeend', '<li class="item">Hello world!</li>');
list.insertAdjacentHTML('beforebegin', '<h1>My List</h1>');

The possible locations are beforebegin, afterbegin, beforeend and afterend. The insertAdjacentHTML method is a beauty because it create a DOM element from your HTML string and place it into the document (really useful for template engines and it’s faster than innerHTML).