Sonny
Sonny

Reputation: 8326

jQuery Child Event Handling

I have a container element. The element may or may not have anchor tags in it. I want to listen for click events within that element. I want to handle each click only once, but I want to do something different if an anchor tag is clicked.

Issues that I've run into:

How do I accomplish this?

Upvotes: 0

Views: 49

Answers (2)

emerson.marini
emerson.marini

Reputation: 9348

You can check the target of the click. And as you seem to be trying to enable the click just once for every element within the container, you should then use .one():

$(function() {
    $("#container").children().one("click", function(e) {        
        e.preventDefault(); // For testing purposes.
        
        if ($(e.target).parents().is("a") || $(e.target).is("a")) {
            // Anchor.
        }
        else {
            // Others...
        }
    });
});

Demo

That's an improvement to the example I've posted in the comments previously.

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

This should work:

$('#ID').on('click', function(e) {
    if ($(e.target).closest("a").length) {
        anchorWasClicked();
    } else {
        somethingElseWasClicked();
    }
});

Upvotes: 1

Related Questions