0

Fiddle

I can of course take the .inner layer out of .main layer and then use absolute position against another wrapper i.e .outer layer to place it in the same position and this will stop it from triggering .main click event. but I was wondering if there's an easier way to avoid having both click events fire if both child element and parent trigger a click event.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
LaserBeak
  • 3,257
  • 10
  • 43
  • 73

2 Answers2

1

you can use stopPropagation()

$(document).ready(function() {
    $('.outer').on("click",".main",function() { alert('main clicked'); })
    $('.outer').on("click",".inner",function(e) {e.stopPropagation(); alert('inner clicked'); })
});

http://jsfiddle.net/5xvkM/6/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

Use stopPropagation(). Even if both are delegated events, jQuery evaluates them deepest first. Since the inner most has stopPropagation(), the events higher up in the order are not executed.

$('.outer').on("click", ".inner", function(event) {
    event.stopPropagation();
    alert('inner clicked');
});

But you'll have to note the order of execution between direct handlers and delegated handlers. Since events need to bubble to reach the delegated handlers, direct handlers are fired first. Stopping propagation using delegated handlers would be useless when direct handlers are in the mix.

Joseph
  • 117,725
  • 30
  • 181
  • 234