I am trying to understand data mutations that are occurring client-side after an event is triggered, but I cannot locate the event triggering logic. Given the following page, I have created two buttons which have events bound:
<html>
<button onClick="console.log('Inline button clicked')">Inline Button</button>
<button id="x">Bound Button</button>
<script>
document.getElementById("x").addEventListener("click", (event) => {
console.log("JS Bound clicked")
});
</script>
</html>
I can determine what will occur when the following button is clicked with the JavaScript document.getElementsByTagName("button")[0].onclick
, however this does not work for the second.
How can I determine if clicking on an element will trigger an event without clicking on the button.
As an extension, is it possible to configure a browser debugger to break on the next (significant) event, without knowing which event will be triggered?
2
Answers
To determine if an element will trigger an event without clicking on it, you can inspect the event listeners attached to the element.
Issue:
You want to find out if clicking on an element will trigger an event without actually clicking it, especially for events bound using JavaScript like
addEventListener
.Solution:
Use the browser’s developer tools or a script to inspect the event listeners attached to the element. I will updated the code, please check this.
In console if you need you can use directly in the browser
console.log(getEventListeners(document.getElementById("x")));
getEventListeners(document.getElementById("x"))
usually gives you the event Listeners registered to your dom element. In most cases this should give you a reliable check for what is executed.That said there are some edge cases you might want to consider depending on your app/design.
I can’t answer the second part with certainty for your case but I usually use
debugger;
hardcoded everywhere where the event might occur + some if logic (e.g. via Event type) & then step through the event bubbles. You could also create a conditional breakpoint e.g. for chrome which is basically the same as a hardcoded version with if.