0

Perhaps a silly question but...

In this simple code:

 $(".Q").on("click", ".container", containerClick);
 $(".Q").on("click", ".container .oneElement", oneElementInContainerClicked);

if .oneElement in .container is clicked, first oneElementInContainerClicked is called.

Is is possible to force the order of events such that containerClick is called first, then oneElementInContainerClicked?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Greg Bala
  • 3,563
  • 7
  • 33
  • 43
  • _"Is is possible to force the order of events such that containerClick is called first, then oneElementInContainerClicked"_ Is expected result for both click handlers to be called ? – guest271314 Dec 02 '15 at 18:35
  • One approach could be to manually invoke `containerClick` (or the logic that *it* invokes, preferably) from within `oneElementInContainerClicked` in the order that you want, and then stop the event propagation for the other handler isn't called. – David Dec 02 '15 at 18:35
  • That concept is called event capturing..http://stackoverflow.com/questions/17249125/event-capturing-jquery – Pardeep Dhingra Dec 02 '15 at 18:45
  • thank you all, yes, I know i can do that (manually call the other event), but was wondering if there was another way. it seems like there is not – Greg Bala Dec 02 '15 at 18:53
  • That's default event bubbling behaviour. Why would you want to change that? What is the problem you are facing with the order? – Bergi Dec 02 '15 at 18:56
  • @bergi because it would allow me to change some functionality without touching the contents of both event handlers – Greg Bala Dec 03 '15 at 18:27

1 Answers1

1

Try including check for e.target within containerClick ; calling .trigger("click") on $(this).parents(".container") within oneElementInContainerClicked

function containerClick(e) {
  if (e.target.className !== "oneElement")
    console.log("container")
} 

function oneElementInContainerClicked() {
  console.log("oneElement");
  $(this).parents(".container").trigger("click")
} 


$(".Q").on("click", ".container", containerClick);
 $(".Q").on("click", ".container .oneElement", oneElementInContainerClicked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="Q">
  <div class="container">container
    <div class="oneElement">oneElement</div>
  </div>
  </div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • @GregBala Note, while re-reading Question, appear that `$(this).parents(".container").trigger("click")` should be called before `console.log("oneElement");` within `oneElementInContainerClicked` to return expected results ? – guest271314 Dec 02 '15 at 18:55