Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function before any click event handler

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.

like image 242
atul bajpai Avatar asked Jan 28 '16 06:01

atul bajpai


People also ask

How do you call a function on a click?

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.

How do I trigger a click event without clicking?

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.

Is event listener better than Onclick?

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.


1 Answers

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

like image 116
jfriend00 Avatar answered Oct 03 '22 14:10

jfriend00