Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event on click on a div except a link

Tags:

jquery

I want to fire an event when I click on a div, but i don't want that event to fire if i click on a specific link on that div:

my JS

$("#myDiv").not("#myLink").click(function () {
    alert("clicked");
});

//Or

$("#myDiv:not(#myLink)".click(function () {
    alert("clicked");
});

$("body").on('click', '#myLink', function(e) {
    e.stopPropagation();
});

my HTML

<div id="myDiv">
    <a href="#" id="myLink">Some link</a>
</div>

Here is jsfiddle

EDIT: Actually my real code is with "On" method, I've already tried stopPropagation but it doesn't work in that case

like image 620
Anas Avatar asked Apr 14 '13 16:04

Anas


1 Answers

In order to get your desired result you have to register an event handler on the anchor element, that when executed blocks the event propagation.

$("#myLink").click(function(e) {
    e.stopPropagation();
});

Why this work?

Events propogate starting from the root element till the target element (capture phase) and after reaching the target, they climb up back to the root element (bubbling phase). The target element is the element that received the event.

It's possible to register event listeners both on the capture phase, both on the bubbling phase. Here, we're using jQuery that registers the event on the bubbling phase.

stopPropagation permits to block the event propagation through the DOM.

That's an article I wrote, in case you need more info about W3C event model.

like image 93
Bruno Avatar answered Oct 13 '22 02:10

Bruno