Wancieho Wancieho - 8 months ago 82
jQuery Question

Extend jQuery on click event

I need to find a global way to prevent jQuery on('click') events from firing if an anchor has the disabled="disabled" (yes im aware this isn't a valid attribute of an anchor) attribute set. The anchor could also be dynamically set to disabled at any time.

Another problem is firing order as im working within a "framework" and the App class loads first and subsequent classes with anchor events load after. Ideally id like to have something inside the App class that prevents the "child" class events from firing but at the moment the child class events fire first and then the App events so using stopPropagation() doesn't work either.

I'm wary of some solutions like How to order events bound with jQuery as you can see this could break between jQuery versions.


Delegating event would work if click event propagation not stopped:

$(document).on('click', 'a[disabled]', function(e){

Otherwise, you could use CSS rule:

a[disabled] {
  pointer-events: none;

And if you want an event to fire on parent level before any of its descendants, capture it, e.g:

document.addEventListener('click', function(e){
  if($(e.target).closest('a[disabled]').length) {
    // do something which be fired before any click handler bound to `.parentClass *`
    // e.g prevent any other event
    // and prevent default anchor click behaviour
}, true);