Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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");         });     } 
like image 530
Kevin Karl Leaño Avatar asked Jan 20 '15 22:01

Kevin Karl Leaño


People also ask

How do you check if element already has an event listener?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .

How do you check if there is an event listener in JavaScript?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

Can I use getEventListeners?

getEventListeners(obj) is only a Google Chrome specific Command Line Tool feature. This means that you can only use this feature inside Chrome Dev Tools when manually typing into the console. You cannot use this method in your actual JavaScript source code.


1 Answers

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.

like image 144
arufian Avatar answered Nov 10 '22 01:11

arufian