Jack Zhang Jack Zhang -4 years ago 131
Javascript Question

"DomContentLoaded" isn't working in my browser?

I wrote my html page like this:

<div>
<img src="Natural1.jpg" id="img1" >
<audio src="sound.mp3" id="audio1" ></audio>
</div>


And my javascript file is this:

function init(){
audio1 = document.getElementById("audio1");
var img1 = document.getElementById("img1");
img1.addEventListener("click", imgClick, false);
}
function imgClick(){
if(audio1.paused){
audio1.play();
}
else{
audio1.pause();
}
}
document.addEventListener('DomContentLoaded', init, false);


I run that in chrome12, the script first execute the
document.addEventListener
method, but it did not go into the init method, why?
I tried
attachEvent
method instead
addEventListener
in IE8, but it still doesn't.
what's wrong with my code?

Answer Source

Might be the casing of th event name. Try the following instead:

document.addEventListener('DOMContentLoaded', init, false);

Pretty sure this is the case. I tested the following:

document.addEventListener("DomContentLoaded", function(){ alert('Dom') }, false);
document.addEventListener("DOMContentLoaded", function(){ alert('DOM') }, false);

On jsbin, and the latter event was raised alone. Note, IE8 will not raise this alert since this event doesn't take place there. Instead, you will find success from IE9 and IE10.

Example: http://jsbin.com/ocidok/edit#javascript,html

Browser support for DOMContentLoaded is cataloged on the Mozilla Developer Network. As of today, this event is only available in the following browsers:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download