kraftwer1
kraftwer1

Reputation: 5731

jQuery control order of click events

Let's say we have this:

$(document.body).on("click", "div", function() {
    console.log(1);
});

$("div").on("click", function() {
    console.log(2);
});

Now when I click on the <div>, the output is:

2
1

Is there a way to have the opposite order, given the fact that I can't modify the selectors or change the order?

EDIT

My current workaround is a setTimeout(), but I'd prefer not to have this since it creates ugly glitches.

Upvotes: 1

Views: 79

Answers (2)

Fenixp
Fenixp

Reputation: 645

The event propagates up trough DOM, so there's no practical way of forcing click on body to fire before the click on div does. However, a simple workaround to this issue would be following:

var somethingOrOther = function() {
  console.log(1);
}

$(document.body).on("click", "div", function() {
    somethingOrOther();
});

$("div").on("click", function(event) {
    event.stopPropagation();
    somethingOrOther();
    console.log(2);
});

event.stopPropagation(); ensures that the click won't bubble further up the DOM and click on body won't trigger, but only when clicking the div.

Upvotes: 1

emrhzc
emrhzc

Reputation: 1480

You said nothing about modifying callback function

$(document.body).on("click", "div", function() {
   setTimeOut(function(){ console.log(1);},5});
});

$("div").on("click", function() {
    console.log(2);
});

Upvotes: 0

Related Questions