chris cozzens
chris cozzens

Reputation: 517

When creating an event listener, function is firing right away

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

Answers (4)

John Meade
John Meade

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

null
null

Reputation: 1162

call that function like below

function firstImageClick(){
   //add event listener 
   document.getElementById("firstStep").addEventListener("click", 
   myFunction);
}

remove parenthesis from myFunction.

Upvotes: 1

Oscar Paz
Oscar Paz

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

ry4nolson
ry4nolson

Reputation: 859

The parameter should be myFunction instead of myFunction().

Upvotes: 3

Related Questions