Let's say you have an structure in which an element contains another, and both will trigger a different action when clicked. How do you avoid that the beneath element triggers its action when the above element is clicked?
To prevent that, you can assign a class to the inner element, and then adjust your JQuery code as follows:
This div has a click action
This link has a click action
This link has a click action
To prevent that, you can assign a class to the inner element, and then adjust your JQuery code as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <script> $(function(){ $("#beneathelement").on("click", function(e){ e.preventDefault(); if(e.target.className.indexOf("innerclass") < 0){ //this does the trick alert('beneath clicked'); } }); $("#aboveelement").on("click", function(e){ e.preventDefault(); alert('above clicked'); }); }); </script> <!-- below is the HTML code for the elements --> <div id="beneathelement"> <p>This div has a click action</p> <a href="#" id="aboveelement" class="innerclass">This link has a click action</a> </div> |