Reputation: 8326
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:
$('#ID').on('click', myFunction);
$('#ID').find(*).on('click', myFunction);
How do I accomplish this?
Upvotes: 0
Views: 49
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...
}
});
});
That's an improvement to the example I've posted in the comments previously.
Upvotes: 1
Reputation: 51330
This should work:
$('#ID').on('click', function(e) {
if ($(e.target).closest("a").length) {
anchorWasClicked();
} else {
somethingElseWasClicked();
}
});
Upvotes: 1