I\'m currently using jQuery to make a div clickable and in this div I also have anchors. The problem I\'m running into is that when I click on an anchor both click events ar
ignoreParent() is a pure JavaScript solution.
It works as an intermediary layer that compares the coordinates of the mouse click with the coordinates of the child element/s. Two simple implementation steps:
1. Put the ignoreParent() code on your page.
2. Instead of the parent's original onclick="parentEvent();", write:
onclick="ignoreParent(['parentEvent()', 'child-ID']);"
You may pass IDs of any number of child elements to the function, and exclude others.
If you clicked on one of the child elements, the parent event doesn't fire. If you clicked on parent, but not on any of the child elements [provided as arguments], the parent event is fired.
ignoreParent() code on Github
If you do not intend to interact with the inner element/s in any case, then a CSS solution might be useful for you.
Just set the inner element/s to pointer-events: none
in your case:
.clickable > a {
pointer-events: none;
}
or to target all inner elements generally:
.clickable * {
pointer-events: none;
}
This easy hack saved me a lot of time while developing with ReactJS
Browser support could be found here: http://caniuse.com/#feat=pointer-events
Here my solution for everyone out there looking for a non-jQuery code (pure javascript)
document.getElementById("clickable").addEventListener("click", function( e ){
e = window.event || e;
if(this === e.target) {
// put your code here
}
});
Your code wont be executed if clicked on parent's childs
you can also try this
$("#clickable").click(function(event) {
var senderElementName = event.target.tagName.toLowerCase();
if(senderElementName === 'div')
{
// do something here
}
else
{
//do something with <a> tag
}
});