Check if an element has event listener on it. No jQuery

Javascript

Javascript Problem Overview


How to check if an element has event listener on it, if I use an inline function on it like the code below? Because I have a function that recalls the function and add the event listener, but it cause to have duplication event listener causing it to trigger a function twice. How can I check it so I can prevent it to add an event listener if is it already exist?

for (var a = 0;a<formFieldInput.length;a++) {
    if(formFieldInput[a].hasAttribute("name") && formFieldInput[a].attributes.title.value !== "Valid Until") {
	    formFieldInput[a].addEventListener("click",function(event) {
		    toggleFieldList(event,"show");
	    });
    }

Javascript Solutions


Solution 1 - Javascript

Since 2016 in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.

getEventListeners(document.querySelector('your-element-selector'));

Caution: This solution is only works for Chrome developer tools.

Solution 2 - Javascript

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: https://stackoverflow.com/questions/11455515/how-to-check-whether-dynamically-attached-event-listener-exists-or-not

Solution 3 - Javascript

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

> If multiple identical EventListeners are registered on the same > EventTarget with the same parameters, the duplicate instances are > discarded. They do not cause the EventListener to be called twice, and > they do not need to be removed manually with the removeEventListener > method. > >Note, however that when using an anonymous function as the handler, such listeners will NOT be identical, because anonymous functions are not identical even if defined using the SAME unchanging source-code called repeatedly, even if in a loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin Karl Lea&#241;oView Question on Stackoverflow
Solution 1 - JavascriptarufianView Answer on Stackoverflow
Solution 2 - JavascriptRyan WarnerView Answer on Stackoverflow
Solution 3 - JavascriptRonnie RoystonView Answer on Stackoverflow