atul bajpai
atul bajpai

Reputation: 155

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.

Upvotes: 7

Views: 34977

Answers (2)

Michael Kapustey
Michael Kapustey

Reputation: 173

I see two solutions here.

First is to use onmousedown that is fired before click event

document.querySelector('.selector').addEventListener('mousedown', function(){
    console.log('mousedown');
}

document.querySelector('.selector').addEventListener('click', function(){
    console.log('click');
}

Other way is to use compose that will create new reusable function for you (npm i lodash.compose).

var compose = require(lodash.compose);
var firstFunc = function(e){
    console.log('first');
    return e; //if you want to use it in second function
};
var secondFunc = function(e) {
    console.log('second');
};

document.querySelector('.selector').addEventListener('click', compose(secondFunc, firstFunc));

Or you could save new func in variable;

var logFirstThanSecondOnClick = compose(secondFunc, firstFunc);
document.querySelector('.selector').addEventListener('click', logFirstThanSecondOnClick);

Simply compose do next

function compose(f, g) {
    return function(x) {
        return f(g(x));
    }
}

But lodash one is more complex inside.

Here is some math theory about function composition, if you are interested in https://en.wikipedia.org/wiki/Function_composition

Upvotes: 6

jfriend00
jfriend00

Reputation: 707308

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

Upvotes: 11

Related Questions