Reputation: 517
I am writing a function that when clicking on an image, it will add an event listener to another image. When creating the event listener, myFunction() is being called right away and not waiting for the click on #firstStep
function firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click", myFunction());
}
Upvotes: 0
Views: 64
Reputation: 162
The parenthesis make the function fire straight away. Change the end of your snippet by taking out the parenthesis.
("click", myFunction());
to ("click", myFunction);
Upvotes: 0
Reputation: 1162
call that function like below
function firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click",
myFunction);
}
remove parenthesis from myFunction
.
Upvotes: 1
Reputation: 18292
You're not adding the myFunction
as callback, but the return of the call to myFunction
.
You must pass the function, not invoke it:
enfunction firstImageClick(){
//add event listener
document.getElementById("firstStep").addEventListener("click", myFunction);
}
Upvotes: 2