neorg
neorg

Reputation: 25

addClass doesn't work (jQuery)

I'm new in jQuery and I need some help. I have a little problem with addClass

Here is HTML:

<div class="first">
    Container 1
    <div class="second hide">
        Some text 1
        <div class="close">close</div>
    </div>
</div>
<div class="first">
    Container 2
    <div class="second hide">
        Some text 2
        <div class="close">close 2</div>
    </div>
</div>

And jQuery

$("div.first").click(function() {
    $("div.first").find("div.second").addClass('hide');
    $(this).find("div.second").removeClass('hide');
});

$("div.close").click(function() {   
    $("div.close").parent().addClass('hide');
    $(this).parent().addClass('hide');
});

What I need.

  1. click container 1.1 -> show container 1.2
  2. click container 2.1 -> show container 2.2, hide container 1.2
  3. click container 1.1 -> show container 1.2, hide container 2.2

and all I listed above works.

Now I need to hide all containers x.2 when "close" is clicked. I think there is a conflict, but I don't know where.

here is http://jsfiddle.net/E69AN/2/

Upvotes: 1

Views: 1953

Answers (2)

suhailvs
suhailvs

Reputation: 21740

when you click on the .close div, this will lead to call 2 click functions, because it is inside the div.first.

  1. First it execute $("div.close").click(fu...., which will lead to hide the div.first
  2. Immediatly it execute $("div.first").click(fu...., which will lead to show the div.first

you can prevent this behaviour by e.stopPropagation();:

 $("div.first").click(function() {
    $(".second").hide();
    $(this).find(".second").show();
});

$("div.close").click(function(e) {    
    e.stopPropagation();
    $(this).parent().hide();
});

jsfiddle

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337733

You need to stop the propagation of the click event on the close button, otherwise you are clicking close, and then immediately re-opening the div. Try this:

$("div.first").click(function() {
    $("div.second").addClass('hide');
    $(this).find("div.second").removeClass('hide');
});

$("div.close").click(function(e) {   
    e.stopPropagation();
    $(this).closest('.second').addClass('hide');
});

Updated fiddle

Upvotes: 3

Related Questions