Robbert
Robbert

Reputation: 1330

Second time clicking div closes and directly opens

I'm working on a menu wich I can expand and collapse. When I click it my code works fine and collapses the div. And if I click again on my open en close div it opens fine also. But The second time doing this procces my div closes and opens directly. Can someone tell what I'm doing wrong..


$( document ).ready(function(e) {

    // Collapse and expand
    $("#collapse").click(
        function() {
            $("#information").fadeOut(200);
            $("#leftColumn").animate({width:"10px"}, 200);
            $("#collapse").html("»");

            $(this).click(function() {
                $("#information").fadeIn(200);
                $("#leftColumn").animate({width:"250px"}, 200);
                $("#collapse").html("«");

            });
        }
    );


});

Upvotes: 0

Views: 1491

Answers (3)

adeneo
adeneo

Reputation: 318182

$(document).ready(function() {
    $("#collapse").on('click', function() {
        var w = parseInt( $("#leftColumn").css('width'),10 ) > 11;
        $("#information").fadeToggle(200);
        $("#leftColumn").stop(true,true).animate({width: w ? 10 : 250}, 200);
        $("#collapse").html(w ? "»" : "«");
    });
});

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

var toggle=0;
$("#collapse").click(function() {
    if(toggle==1){
        $("#information").fadeIn(200);
        $("#leftColumn").animate({width:"250px"}, 200);
        $("#collapse").html("«");
        toggle=0;
    }
    else
    {
        $("#information").fadeOut(200);
        $("#leftColumn").animate({width:"10px"}, 200);
        $("#collapse").html("»");
        toggle=1;
    }
});

Upvotes: 0

axel.michel
axel.michel

Reputation: 5764

You override the first onclick function - that's why you have to handle your expand/collapse a bit different. This variant simply adds and removes a class to decide which animation should be used:

( document ).ready(function(e) {
    // Collapse and expand
    $("#collapse").click(
        function() {
            // default case
            if(!$(this).hasClass('collapsed')) {
                $(this).addClass('collapsed');
                $("#information").fadeOut(200);
                $("#leftColumn").animate({width:"10px"}, 200);
                $("#collapse").html("»");
            } else {
                // and in case it is collapsed...
                $(this).removeClass('collapsed');
                $("#information").fadeIn(200);
                $("#leftColumn").animate({width:"250px"}, 200);
                $("#collapse").html("«");
            }
        }
    );
});

Upvotes: 0

Related Questions