Reputation: 749
I cant think straight today, can someone show me the correction that I cannot find right now? I realize im doing something silly I just cannot find. Basically the second function should close the box, but its not working at all.
if (!$('div').hasClass('active')) {
$("span").click(function () {
$("div").stop().animate({ height: "360px" });
$("div").addClass('active');
});
}
if ($('div').hasClass('active')) {
$("span").click(function () {
$("div").animate({ height: "0px" });
$("div").removeClass('active');
});
}
Upvotes: 1
Views: 56
Reputation: 144689
Your if
statements are executed just once and as only one of the conditions can be true, you will have just one handler which won't do what you expect, you should move the logic to your click
handler:
var $div = $('div');
$("span").click(function () {
var h = $div.toggleClass('active')
.hasClass('active') ? '0px' : '360px';
$div.stop().animate({ height: h });
});
Upvotes: 2
Reputation: 818
You need to contextualize your inner calls to jQuery, you are calling them on ALL divs not just the 'active'
ones.
$("div").stop().animate({ height: "360px" });
$("div").addClass('active');
these lines are not specific to a div. without knowing exactly what you need to do I don't know what the right value is here, but probably higher up you need something like this:
if ($('div').hasClass('active')) {
var myDiv = this;
$("span").click(function () {
furthermore this span
isn't contextualized either which span, one in the div
? you could do:
$("span", this).click(function () {
Upvotes: 1
Reputation: 8728
You never add the second .click-event because the condition $('div').hasClass('active')
is not guilty at loading your page...
Upvotes: 1
Reputation: 16223
The problem is that your event should be triggered on click, the way you have it, it checks for the class active
just once, and then defines 1 click function (you only need 1). So try this:
$("span").click(function () {
if (!$('div').hasClass('active')) {
$("div").stop().animate({ height: "360px" }).addClass('active');
} else {
$("div").animate({ height: "0px" }).removeClass('active');
}
});
Upvotes: 1
Reputation: 3657
Your issue is that you are binding multiple event handlers based on a condition, rather than binding one event handler and checking the condition within the handler:
$("span").click(function () {
if($('div').hasClass('active'))
$("div").animate({ height: "0px" }).removeClass('active');
else
$("div").stop().animate({ height: "360px" }).addClass('active');
});
http://jsfiddle.net/fmpeyton/BW8LM/
Upvotes: 1