Realbitt
Realbitt

Reputation: 408

get target clicked div even if it inside other divs (Just the target div and one event for it)

how can i get target clicked element even if this element inside other elements with same type like (div)

i have 3 divs inside each others , when i declare click events for div and i clicked top div i got 3 click events for the parents too.

so i want just one click events for the target element i clicked and ignore the others

My Try

jQuery('div').click(function(e) {
    var clicked = jQuery(e.target);
    // Ensure we're checking which list item is clicked,
    // other children should be allowed
    if(clicked.parents().length > 0) {
        // :first ensures we do not select higher level list items
        alert($(clicked).html());
return ;    
    }
else
{
    alert($(clicked).html());
}

});

Upvotes: 2

Views: 4239

Answers (3)

lonesomeday
lonesomeday

Reputation: 237845

Doing stopPropagation is one method. Rather nicer, I think, is to check if the current element is the same as the event target, which means you can still handle events with handlers higher up the tree:

jQuery('div').click(function(e) {
    if (this === e.target) {
        // we're handling on the clicked element
    }
}

Upvotes: 1

sevenseacat
sevenseacat

Reputation: 25029

You need to stop the click event propagating up the DOM tree.

http://api.jquery.com/event.stopPropagation/

Upvotes: 0

Brian Flanagan
Brian Flanagan

Reputation: 4632

Your could try adding e.stopPropagation() inside your click event handler. This will allow the event to trigger on whichever div was clicked, but stop the event from going any further up the dom.

Upvotes: 3

Related Questions