mweis mweis - 4 months ago 20
jQuery Question

How do I combine the animation and toggle event?

I am clicking toggle three times and the nav is disappearing if the user clicks the button three times. It toggles fine if the user makes just one click or even two. But three at once makes the nav disappear on 200px. It disappears at 50px fine with only one or two clicks.

Any ideas why?

$("#toggle-button").click(function() {
var toggleWidth = $('#cgDiv', window.parent.document).width() == 200 ? “50px" : “200px";
$('#cgDiv', window.parent.document).animate({ width: toggleWidth });
$('nav').toggle();
});


I tried combining the toggle in the
toggleWidth
event however I am getting the same problem of 3 clicks making the nav disappear.

$("#toggle-button").click(function() {
var toggleWidth = $('#cgDiv', window.parent.document).width() == 200 ? “50px" : “200px";
$('#cgDiv', window.parent.document).animate({
width: toggleWidth
}, function(){
$('nav').toggle();
});
});

Answer

You could keep track of the hide/show status in a variable. You should also use .stop() to stop the animation before starting it again.

var shown = false;
$('#toggle-button').click(function() {
    shown = !shown;
    if (shown) {
        $('#cgDiv').stop().animate({ width: '200px' }, function() {
            $('nav').show();
        });
    } else {
        $('nav').hide();
        $('#cgDiv').stop().animate({ width: '50px' });
    }
});

jsfiddle

UPDATE

Since you mention in a comment that you do not want the user to interrupt the animation, you could disable the button during the animation, like this:

$('#toggle-button').click(function() {
    var $button = $(this).attr('disabled', true);
    if ($('#cgDiv').width() == 50) {
        $('#cgDiv').animate({ width: '200px' }, function() {
            $('nav').show();
            $button.attr('disabled', false);
        });
    } else {
        $('nav').hide();
        $('#cgDiv').animate({ width: '50px' }, function() {
            $button.attr('disabled', false);
        });
    }
});

jsfiddle