jthomas jthomas - 3 months ago 8
Javascript Question

Why does addEventListener for load event not work with a function literal?

When adding an event listener for the

load
event I have to use either a function call or a self invoking function for it to work. I can't just use a function literal like I do for the click event. Why can't I use a function literal like I do for my click event?

<body>
<div>some content</div>
<script>
var div = document.getElementsByTagName("div")[0];
// does not work (console is not written to when page loads)...
div.addEventListener("load", function(){console.log("div load event")}, false);
// works (console is written to when div content is clicked...
div.addEventListener("click", function(){console.log("div click event")}, false);
</script>
</body>

Answer

The load event fires in elements which load external contents, such as img, iframe, etc.

The truth is load event may not fire case a content load before the event is declared. So, if you want the load event to work, you need to declare it before a src or href, for example.

Once the div is declared it's already loaded. So it's impossible to fire a event like this in the div.

If you want to know the div, including its elements such as img have loaded, you must declare the load event for each, i.e:

var loaded = 0;

var images = div.getElementsByTagName("img"),
    len = images.length;

function imgload() {
    if(++loaded > len) {
        console.log("Div loaded.");
    }
}

for(var i = 0, img; img = images[i]; i++) img.addEventListener("load", loaded);