开发者

JQuery and showing / hiding content

Why does this not work? I have开发者_StackOverflow中文版 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


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/


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜