Hi I want to call a function every time before any click event handler method. I know, inside the click handler method I can call my function first, but this quite cumbersome as I have to do this at so many place as well as I have to keep in mind the same for any future click events.
Method 1: Use addEventListener() Method Get the reference to the button. For example, using getElementById() method. Call addEventListener() function on the button with the “click” action and function passed as arguments.
If you want to trigger click event without clicking a button manually, then you should use the click() method in Javascript. Example : click button on page load dynamically. For that we will create a button with an id my-btn . So that, we can select the button using the getElementById() method.
Summary: addEventListener can add multiple events, whereas with onclick this cannot be done. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements.
You can set a capture event handler on the document
object (or any common parent) and it will be called first before the event handler on the individual object. capture
is the third argument to .addEventListener()
which is normally optional and defaults to false
, but if you pass true
on a parent, then the event handler will be called first.
Here's an example:
document.addEventListener("click", function() {
log("document capture click");
}, true);
document.getElementById("target").addEventListener("click", function() {
log("element click");
}, false);
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
<div id="target">Some text to click on</div>
Here's a related question that helps to understand the capture flag: Unable to understand useCapture attribute in addEventListener
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