Alexis Wilke
Alexis Wilke

Reputation: 20720

Can we detect whether a link was clicked within a DIV that has a jQuery.click()?

I'm wondering whether there is an easy way to detect a click on a link that appears within a div on which I want to handle clicks...

So, there is an simple example of HTML code:

<div class="checkmark">
    <div class="box">&nbsp;</div>
    <div class="label">Checkbox label possibly <a href="/random" target="_blank">with an anchor</a>.</div>
</div>

So in this example, I use a set of <div> tags to create a checkmark. The "box" is where I show a little square and when checked, also show the checkmark (a red cross, for example.)

To make the checkmark work as expected, I use jQuery and capture mouse clicks on the main <div> tag:

jQuery("checkmark").click(function(e){
    e.stopPropagation();
    e.preventDefault();

    jQuery("box", this).toggle("checked");
});

Pretty easy, that works great (the "checked" class is enough to show a checkmark since that can be defined using CSS.)

However, as we can see in the example, the "label" includes an anchor. If I click the anchor, the jQuery I just presented runs, but the anchor does nothing. If I remove the stopPropagation() and preventDefault() the anchor gets clicked, but the checkmark is toggled too.

What I'm wondering is: is there an easy way to check whether the propagation would trigger the anchor and in that case just ignore the click in the "checkmark" code?

Something like that:

jQuery("checkmark").click(function(e){
    if(!(anchor.clicked()))  // how do we do this?
    {
        e.stopPropagation();
        e.preventDefault();

        jQuery("box", this).toggle("checked");
    }
});

P.S. I do not know whether there are anchors in the label. So the discovery has to happen in the click() function (unless there is a better setup and that "if" could happen differently).

Note: here I show a target="blank" parameter. In the real deal I will actually open a popup, but that doesn't really make a difference here.

Upvotes: 3

Views: 2328

Answers (3)

VtoCorleone
VtoCorleone

Reputation: 17203

You could use the event delegateTarget property to see which DOM element triggered the event.

if($(e.delegateTarget).is("a"))
    // execute code

Upvotes: 0

Guffa
Guffa

Reputation: 700212

You can just add this handler:

jQuery("checkmark a").click(function(e){
  e.stopPropagation();
}

It will stop the click event from bubbling from the link to the div, so the link will be activated, and the event never reaches the div where it would be stopped.

Upvotes: 0

dsgriffin
dsgriffin

Reputation: 68576

This is what event.target is for.

For example, in this case:

if($(e.target).is("a")) { 
   // It was the anchor element that was clicked
}

jsFiddle here

Upvotes: 7

Related Questions