Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event listener added on click but runs straight away?

Tags:

javascript

I add an event on click of my button:

this.$refs.btn.addEventListener('click', this.turnOn);

In the turnOn method I add a listener on the document, to run the turnOff method.

turnOn() {
    document.addEventListener('click', this.turnOff);
}

Then during testing, I click the button and the turnOn method runs, but that initial click also runs the document click listener.

How can I run the turnOn method, add the document listener, but not run the document click listener on the initial button click?

like image 635
panthro Avatar asked Mar 25 '19 11:03

panthro


People also ask

Why is my add event listener not working?

If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.

How do I stop event listener after clicking?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

How do you make an event listener only work 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.


1 Answers

This is due to event bubbling.When you click on <button> an eventListener is attached to body and after that due bubbling its called.
You can prevent that using event.stopPropgation(). Below are two snippets to see the difference.

Non-Working

document.querySelector('button').addEventListener('click',(e)=>{
  document.addEventListener('click',()=>console.log("body clicked"));
  console.log("button clicked")
})
<body>
<button>Test</button>
</body>

Note: The above non-working example also adds multiple click events on each click on Test

Working

document.querySelector('button').addEventListener('click',(e)=>{
  e.stopPropagation();
  document.addEventListener('click',()=>console.log("body clicked"));
  console.log("button clicked")
})
<body>
<button>Test</button>
</body>
like image 51
Maheer Ali Avatar answered Oct 17 '22 05:10

Maheer Ali