Ibolit
Ibolit

Reputation: 9740

jQuery, use the right selector

I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the div also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?

Here is the code:

<div class='mainpage'>
    <p class='common'>bla-bla-bla <span class='footnoted' footnote='f1'>foo bar</span></p>
</div>

jQuery code:

$(document).ready(function(){
    $(".mainpage>.common>.footnoted").click(function(){
        alert('a');
    });

    $(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
        alert('b');
    });
});

In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?

Thank you in advance. Timofey.

Upvotes: 0

Views: 105

Answers (2)

Sam Becker
Sam Becker

Reputation: 19656

Depending on which event is firing first, you could try adding return false; to the end of your click event function. That should stop the second click event from firing and fix your problem.

Upvotes: 0

Loktar
Loktar

Reputation: 35319

You need to use

event.stopPropagation();

in the span like so

$('div').click(function(){alert('div clicked');});

$('div span').click(function(event){ 
    alert('span clicked')
    event.stopPropagation();
});

Live Demo

Reference

Upvotes: 3

Related Questions