Java Reference
In-Depth Information
var newImgNumber = Math.round(Math.random() * 3);
while (el.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
el.src = myImages[newImgNumber];
}
function updateStatus(e) {
var el = e.srcElement;
var status = document.getElementById("status");
status.innerHTML = "The image changed to " + el.src;
if (el.src.indexOf("mexico") > -1) {
el.detachEvent("onclick", changeImg);
el.detachEvent("onclick", updateStatus);
}
}
var imgObj = document.getElementById("img0");
imgObj.attachEvent("onclick", updateStatus);
imgObj.attachEvent("onclick", changeImg);
</script>
</body>
</html>
Save the page as ch10_example11.html . Load the page into your browser, and you will see it behave
like ch10_example7.html . Clicking the image results in it changing to a random picture, and the text of
the <div/> element changes to contain the URL of the new picture.
Let's jump right to the code, which is mostly the same as ch10_example7.html . The first big difference
is how you register the event handlers for the image object. Instead of using addEventListener() , you
use old‐IE's attachEvent() method:
imgObj.attachEvent("onclick", updateStatus);
imgObj.attachEvent("onclick", changeImg);
But there's another big difference here. Unlike the standard addEventListener() , the handlers
registered with attachEvent() execute in reverse order. So, you register the handler with the
updateStatus() function before registering with changeImg() .
The next change is in the first statement of the changeImg() function. You want to retrieve the element
that received the event, and old‐IE's event object gives you that information with the srcElement
property:
function changeImg(e) {
var el = e.srcElement;
The rest of the function is left unchanged.
Search WWH ::




Custom Search