Reputation: 2796
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?
Upvotes: 3
Views: 18123
Reputation: 796
JavaScript event names are case-sensitive strings. Therefore, capital and lowercase letters are NOT interchangeable in event names. So, changing the name from 'DomContentLoaded'
to 'DOMContentLoaded'
will fix the issue -- in Chrome at least.
As for IE 8: There's no way. The first version of IE to ever implement the DOMContentLoaded
among other HTML5 events was version 9, so all I can say is: Update your browser! I also noticed that you're using the 16-version-out-of-date Chrome 12, am I right? Seriously, both browsers need to be updated. Outdated browsers pose serious security risks. Good thing I as a Chromebook user am able to keep the most critical component to computer security -- the browser -- up-to-date VERY easily due to its seamless nature...
Upvotes: 0
Reputation: 268424
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:
Upvotes: 8