0

There is code on I do not own that has placed a jQuery delegated event listener on a click event (to collect and fire Omniture data).

$("html").on('click', 'a', function() { /* Stuff */ });

I have written code that also needs delegated events, so I can execute some program behavior on a click event, but I also want the code above to fire as well.

$(".module").on('click', 'a.yes', function(event) { /* My stuff */});

When I put my code in, I can clearly see my event firing, but not the other.

This Stack Overflow answer states that in modern browsers, the event bubbles up. If the event hits an event listener on the way up, the handler at that level fires, but the event continues to bubble up. https://stackoverflow.com/a/4616720/432089

I didn't get any console errors, and maybe the other code isn't configured correctly on my page. Can someone confirm that the event will bubble all the way to the top, all the while activating any matching handler along the way? (provided no event handler is stopping the propagation with event.stopPropagation or return false)

I just want to make sure I fully understand event bubbling, so I know where to begin debugging. (i.e. my code versus code related to Omniture)

Community
  • 1
  • 1
Stephen
  • 2,410
  • 3
  • 33
  • 57

1 Answers1

1

If your event handler does either of these two things, the event will not bubble up:

  1. the function calls event.stopPropagation();
  2. the function returns false (jQuery specific).

The below code demonstrates that behaviour:

$("html").on('click', 'a', function() { alert('base'); });
$(".module").on('click', 'a.yes', function(event) { alert('custom'); });
$(".module").on('click', 'a.yes2', function(event) { alert('custom2'); return false; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="module">
  <a class="yes" href="#">test me</a>
  <a class="yes2" href="#">test me too</a>
</div>
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Thanks for confirming. That means the Omniture code I do not own is not configured properly then. I'm pretty sure there are no other event listeners between my code and the Omniture code that stop the event bubbling. – Stephen Jun 11 '15 at 03:45
  • @Stephen If I'm not mistaken, the Omniture code should be the last one to run .. so it's not likely that it can affect your code. – Ja͢ck Jun 11 '15 at 03:46
  • My click event handler is definitely firing when I look in Chrome Dev Tools. So, I know the Omniture code is not affecting my code. I"m trying to figure out why the Omniture code is not firing. It's either a configuration issue (because I'm on a test page in the CMS which doesn't have everything) or some handler between my code and Omniture has stopped the propagation (unlikely, since production would be affected). Thanks for confirming how event propagation works, because I now know where to debug or ask questions. – Stephen Jun 11 '15 at 10:58