addEventListener(“click”,…) firing immediately [duplicate]

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?



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(){

When you write functionName followed by (), it will call function. If you wish to assign function to a handler, you should do

document.getElementById("tooltip-link1").addEventListener("click", displayTooltip);

Now if you wish to pass parameter to this function, you can either wrap it inside a function like

  .addEventListener("click", function(){displayTooltip(2)});

Or you can use .bind()

  .addEventListener("click", displayTooltip.bind(this, 2));

You need to call this method as a callback. Since you are calling it as displayTooltip(2) you are ultimately calling the function at that line.

What you need to do is to bind a callback rather than calling at that line. Something like

 .addEventListener('event', function()
     { displayTooltip(2) } 

Hope this be of some help

Happy Learning


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.