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?
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.
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.
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.
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) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With