Reputation: 356
Why does this not work? I have looked for tutorials online but they only show how to show/hide with a button. I want to toggle the height of an element.
$('.oldestinititives').mousedown(function() {
$(this).animate({"height": 450}, "slow");
$(this).addClass("pop");
});
$('.pop').mousedown(function() {
$(this).animate({"height": 250}, "slow");
$(this).removeClass("pop");
});
in the CSS, the block is 250px by default. Clicking the element does reveal the content, but clicking it again does not hide it. Using firebug I can see that the class 'pop' is added but it doesn't seem to target it. What is going on?
thanks, Evan
Upvotes: 0
Views: 96
Reputation: 13421
try this (working example http://jsfiddle.net/saelfaer/CyD2g/)
$('.oldestinititives').live("click", function() {
if($(this).is('.pop'))
{
$(this).animate({"height": 250}, "slow", function(){
$(this).toggleClass("pop");
});
}
else
{
$(this).animate({"height": 450}, "slow", function(){
$(this).toggleClass("pop");
});
}
});
i took the liberty to merge your two event handlers in one, as they could have been merged, depending on what you actually do inside the function you could make it even shorter without the big if-else structure...
the idea here is that you use .live("click", function(){});
this will bind the event to any item that ever will be a valid candidate for your selector. even when at the time of executing the code the element does not have the right class name or ID yet.
Upvotes: 0
Reputation: 111
At the time you are hooking the mousedown event to the elements with the pop
class, there are no elements matching this selector. You have to bind the event as you add the class for this to work. Or even better: use delegate or live to bind the events
Upvotes: 0
Reputation: 15835
As you are adding the class at runtime, are you using jquery live()
to bind events? If not please use it:
http://api.jquery.com/live/
Upvotes: 1