Reputation: 20817
I have an Element overlay, that has some functionality when clicked anywhere inside that area:
<div id="overlay">
some html and some <a href="#">links</a>
</div>
Now I would like something else to happen only, if you clicked on a link inside that area:
$('#overlay').click(function() {
if(clicked_element=="a") alert("clicked inside");
else alert("you clicked a link");
});
How can I complete this?
Upvotes: 2
Views: 168
Reputation: 6612
Try this
$('#overlay').click(function(e) {
if (e.target.nodeName === 'A') {
alert("Link clicked");
} else {
alert('overlay clicked');
}
});
Upvotes: 0
Reputation: 324610
First get the event
object: .click(function(e) {
Then its target
property (e.target)
will be the element you clicked. To be sure you get the link, try this:
var target = e.target;
while(target && target.nodeName != "A") target = target.parentNode;
This will be useful for example if you have an image in the link.
Upvotes: 0
Reputation: 16990
$('#overlay').on('click', 'a', function() {
//'this' now refers to clicked link
});
Upvotes: 1
Reputation: 276286
You can use event.target
:
$('#overlay').click(function(e) { // <- note the parameter
alert(e.target); // <- the target
});
In your example, it would be something like:
$('#overlay').click(function(e) {
if(e.target.nodeName == "A"){
alert("clicked inside");
}else{
alert("you clicked a link");
}
});
For completeness, here is a native JavaScript solution:
document.getElementById("#overlay").addEventListener("click",function(e){
alert(e.target);
},false);
If you want to find the closest <a>
to the target you can use jQuery's closest()
Upvotes: 6