Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener("click",...) firing immediately [duplicate]

Tags:

I'm trying to create some appropriately-placed instructional tooltips that users click through to understand how the site interface works. Each tooltip has a "next" link that toggles the visibility of the previous and next tooltips by modifying the classes (and hence, css).

Here's some simplified code that is supposed to do this:

function displayTooltip(t){   //...some code to determine the tooltip IDs "next" and "previous"   document.getElementById(previous).className = "tooltip invisibleTooltip";   document.getElementById(next).className = "tooltip"; }  document.getElementById("tooltip-link1").addEventListener("click", displayTooltip(2)); 

displayTooltip is called immediately (and correctly toggles the class) when I paste this code into the console (or on page load). If I replace displayTooltip with an alert(), it fires when I click, as anticipated. What am I doing wrong?

like image 768
Escher Avatar asked Feb 27 '16 08:02

Escher


People also ask

Why is event listener firing multiple times?

This symptom is indicative that you've registered the same listener more than once. You must remember to deregister events when your component unloads to prevent his problem.

How do you make Eventlistener work only once?

Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.

What is useCapture in addEventListener?

When adding the event listeners with addEventListener , there is a third element called useCapture. This a boolean which when set to true allows the event listener to use event capturing instead of event bubbling. In our example when we set the useCapture argument to false we see that event bubbling takes place.


1 Answers

When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));

You need to pass reference to the function.

Change to below

document.getElementById("tooltip-link1").addEventListener("click", function(){    displayTooltip(2) }); 
like image 178
Jagdish Idhate Avatar answered Oct 10 '22 03:10

Jagdish Idhate