Make onclick handler ignore link clicks
Validation nodeName
event.target
does not work if your links have children (for example, <span>
or <img>
).
Instead, try picking up the tree from event.target
(deepest element) to event.currentTarget
(event the event handler was registered for) and check if any of these elements are available:
$("div").click(function(event) {
if (clickableBetweenTargetAndCurrentTarget(event))
return; // This click was probably already handled.
doSomething();
});
function clickableBetweenTargetAndCurrentTarget(event) {
for (var el = event.target; el && el != event.currentTarget; el = el.parentNode) {
if (isClickable(el))
return true;
}
return false;
}
function isClickable(el) {
// TODO: Customize this as appropriate for your webpage.
return el.nodeName == 'A' || el.nodeName == 'BUTTON';
}
Demo: http://jsbin.com/fojaco/2/
Note that you will need to configure isClickable for your specific webpage; it's hard / impossible to indicate if an element is generally available.
An alternative approach would be to make sure all clickable descendants are called event.preventDefault()
, then your div click listener should only check event.defaultPrevented
(IE9 +). Or descendants could be named event.stopPropagation()
as suggested in another answer , but calling stopPropagation could lead to subtle bugs .
source to share