Code snippets

These are simply little snippets of code to prevent me having to type so much.

Object detection

Check that the browser is capable of understanding the W3C DOM, and isn’t IE/Mac. (Source)

var IEMAC = (navigator.userAgent.indexOf('Mac') != -1 && navigator.userAgent.indexOf('MSIE') != -1);
var W3CDOM = (document.createElement && document.getElementsByTagName && !IEMAC);

Then at the beginning of a function you would use:

if (!W3CDOM) return;

Adding window onload events

Simon Willison said it best: Executing JavaScript onload.

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);

Cancel (default) event

From ‘eatyourgreens’ on accessifyforums, I’m not sure if it works as well for form submissions, but it looks like a useful snippet to use generically.

function cancelEvent(e) {
    if (e && e.preventDefault) {
        e.preventDefault();
    }
    return false;
}

IE Background flicker

I saw this recently, not sure if it’s needed or works, but wanted to record it to find out. It was probably used from mister-pixel.com.

// Fix for IE background image flicker 
try { 
     document.execCommand('BackgroundImageCache', false, true); 
    } catch(e) {}

Leave a Reply

Your email address will not be published. Required fields are marked *