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.
JavaScript
x
9
1
function changePic() {
2
document.getElementById("sound").onclick = transform(document.getElementById("pic"));
3
}
4
5
function transform (pic) {
6
pic.src = "";
7
alert ("done");
8
}
9
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?
Advertisement
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:
JavaScript
1
4
1
document.getElementById("sound").onclick = function() {
2
transform(document.getElementById("pic"));
3
};
4
However, this is the wrong way to add events.
You should call element.addEventListener
/ element.attachEvent
. (or just use jQuery)