Saturday, December 02, 2006

Javascript appendChild problems

We all know IE really sucks, no contest! I've been playing with Lightbox Gone Wild by Chris Campbell. He uses the technique from Lightbox JS by Lokesh Dhakar. This problem appears in Internet Explorer 6 when using the element.appendChild (child) method. The function looks like this:

function addLightboxMarkup() {

bod = document.getElementsByTagName('body')[0];

overlay = document.createElement('div');
overlay.id = 'overlay';

lb = document.createElement('div');
lb.id = 'lightbox';
lb.className = 'loading';
lb.innerHTML = '<div id="lbLoadMessage">'+'<p>Loading</p>'+'</div>';

bod.appendChild(overlay);
bod.appendChild(lb);

}


If the function is loaded in the middle of the document (in DOM: document object), I get this error in Internet Explorer:

Internet Explorer cannot open the Internet site http://localhost/site.

Operation aborted


This problem is probably due to the function being called before the page has finished loading [1].

The fix is to load the function after all the document (in DOM: document object) has been loaded. One way is to use the onload attribute of the body tag.