i’ve learned that you can register body onload like this:
window.addEventListener('load', function, capture); // or attachEvent for ie; capture is true or false
so i tried to register an element onload like this:
document.getElementById(eleid).addEventListener('load', function, capture);
but it gets me error, says “can not call method addeventlistener of null” or something like that.
I think it’s because the document.getElementById(eleid) doesn’t exist yet when the registering occurs. but i need to register it before the element loads, what’s the point of registering an onload function when the element is already loaded? the function will never get called.
so the question is how do i register an element onload function then?
Update:
thanks to NSD, Pekka, and pygorex1, I now know that I can’t register onload event for elements other than body and image
so now the question is, is there a work around?
basically, what I want to do is show a div only if an image is loaded. onload works for images, so that’s no problem. But sometimes the image is cached and loads before the div, and when the function tries to show the div, it can’t find it. In that case, i want the div to show itself as soon as it comes into being.
any help would be appreciated
The short answer is: you’re doing it wrong.
When would the browser fire a theoretical
onloadevent when it encounters a<div>tag? When it’s rendered onscreen? When the element is parsed in the DOM tree?If for some reason you need to detect when an element comes into being (maybe you’re loading HTML via AJAX and injecting it into the DOM) you can set a timer to check for the element via
getElementById()and then do something with it. Or, better yet, search for the element after it’s been loaded dynamically.