Search code examples
javascriptjquerystoppropagation

How to trigger click event only for the clicked-on layer and not its parent too


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.


Solution

  • 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/