Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Hook in some check on all 'click' events

Tags:

javascript

So I have a regular onclick event attached to a few buttons, each function that handles the onclick event does something different (so I can't reuse the same function for both events).

element1.onclick = function() {
    if(this.classList.contains('disabled') {
        return false;
    }
    // For example make an AJAX call
};

element2.onclick = function() {
    if(this.classList.contains('disabled') {
        return false;
    }
    // For example hide a div
};

I'm writing duplicate code for this 'disabled' class check, I want to eliminate this by hooking in some common onclick check then fire the regular onclick event if that check passes.

I know the below won't work but I think it will illustrate what I'm trying to do:

document.addEventListener('click', function() {
    // 1. Do the disabled check here
    // 2. If the check passes delegate the event to the proper element it was invoked on
    // 3. Otherwise kill the event here
});

I'm not using any JavaScript library and I don't plan to, in case someone comes up with 'Just use jQuery' type answers.

EDIT: Had to pass boolean third argument to addEventListener as true and everything is fine.

like image 695
jbaranski Avatar asked Jan 21 '26 11:01

jbaranski


2 Answers

Use event capturing, like so:

document.addEventListener('click', function(event) {
    if (/* your disabled check here */) {
      // Kill the event
      event.preventDefault();
      event.stopPropagation();
    }

    // Doing nothing in this method lets the event proceed as normal
  },
  true  // Enable event capturing!
);
like image 113
broofa Avatar answered Jan 23 '26 03:01

broofa


Sounds like you need to set the capture flag to true and then use .stopPropagation() on the event if a certain condition is met at the target, f.ex:

document.addEventListener('click', function(e) {
    if ( condition ) {
        e.stopPropagation();
        // do soemthing else, the default onclick will never happen
    }
}, true);​​​​​​​​​​​​​​​​​​​​​​

Here is a demo: http://jsfiddle.net/v9TEj/

like image 36
David Hellsing Avatar answered Jan 23 '26 03:01

David Hellsing