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?
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.
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.
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.
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.
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
document.querySelector('button').addEventListener('click',(e)=>{
e.stopPropagation();
document.addEventListener('click',()=>console.log("body clicked"));
console.log("button clicked")
})
<body>
<button>Test</button>
</body>
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