Kevin UI
Kevin UI

Reputation: 292

jQuery Change order of events

Is there a way to change the order in which jQuery events happen? I haven't been able to find a clear answer.

I have an outer and an inner div. Whenever you click on the inner div, the inner div event fires first. Then the outer div events, even though one was created before and after.

https://jsfiddle.net/nLvaehky/5/

$("#outerDiv").on("mousedown", function() {
    alert('outer div clicked!');
});

$("#innerDiv").on("mousedown", function() {
    alert('inner div clicked!');
});

Upvotes: 1

Views: 299

Answers (2)

Pietro Nadalini
Pietro Nadalini

Reputation: 1800

The order of the execution depends on how you put them in your js file (top to bottom, left to right). But in this case it triggers the innerDiv event first because that was the element you clicked. It doesn't matter if you placed the $("#outerDiv").on("mousedown" ...) first.

But it executes the the mousedown event of the outerDiv because the click propagates upwards in the DOM tree, so if you want to stop that propagation you can use the stopPropagation() event mentioned in "Zakaria Acharki" answer.

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Updated fiddle.

You need to stop the event from bubbling to the parent div using stopPropagation() :

$("#outerDiv").on("mousedown", function() {
  alert('outer div clicked!');
});


$("#innerDiv").on("mousedown", function(e) {
  e.stopPropagation();

  alert('inner div clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outerDiv" style="background-color:blue;">
  <br /><br /><br /><br />
  <br /><br /><br /><br />
  <div id="innerDiv" style="background-color:green;">
    <br /><br /><br /><br />
  </div>
  <br /><br /><br /><br />
</div>

Upvotes: 3

Related Questions