rubo77
rubo77

Reputation: 20817

How do I identify the clicked element with jQuery?

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

Answers (4)

Manoj Yadav
Manoj Yadav

Reputation: 6612

Try this

$('#overlay').click(function(e) {
    if (e.target.nodeName === 'A') {
        alert("Link clicked");
    } else {
        alert('overlay clicked');
    }
});

jsFiddle Link

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

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

jammykam
jammykam

Reputation: 16990

$('#overlay').on('click', 'a', function() {
   //'this' now refers to clicked link
});

Upvotes: 1

Benjamin Gruenbaum
Benjamin Gruenbaum

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

Related Questions