Reputation: 25
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.
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
Reputation: 21740
when you click on the .close
div, this will lead to call 2 click functions, because it is inside the div.first
.
$("div.close").click(fu....
, which will lead to hide the div.first
$("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();
});
Upvotes: 2
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');
});
Upvotes: 3