Javascript event firing before action occurs

Tags: , , ,



I am trying to write a script so that when I play an embedded sound object, a picture that I also have embedded will change.

function changePic() {
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
}
    
function transform (pic) {
pic.src = "";
alert ("done");
}

The problem is that when I load the page, the Javascript code automatically runs even though I don’t click play (autostart is set to false) on the sound object. Does anyone have an idea as to what is causing this?

Answer

When you write onclick = transform(...), you’re calling transform and assigning the result to onclick.

You need to set the handler to an anonymous function that calls transform, like this:

document.getElementById("sound").onclick = function() {
    transform(document.getElementById("pic"));
};

However, this is the wrong way to add events.
You should call element.addEventListener / element.attachEvent. (or just use jQuery)



Source: stackoverflow