user1448093
user1448093

Reputation: 157

jquery toggle two animations

Basically I'm trying to toggle between the two different click functions everytime you click the button.

Heres the jquery code:

$("button").click(function () {
    $("#sidebar").animate({ width: '0px' }, 250, function() {
            $(this).hide();
         });
    $("#tabs_container").animate({
        width: "100%"
    }, 500);
    $("#tabs_container ul.tabs li a").animate({
        width: "247px"
    }, 500);
    $("#myElement_wrapper").animate({
        width: "970px"
    }, 500);
});
$("button").click(function(){
    $("#sidebar").show().animate({
        width: "219px"
    }, 500);
    $("#tabs_container").animate({
        width: "781px"
    }, 500);
    $("#tabs_container ul.tabs li a").animate({
        width: "190px"
    }, 500);
    $("#myElement_wrapper").animate({
        width: "720px"
    }, 500);
}); 

thanks

Upvotes: 0

Views: 1449

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219920

That's what toggle is for. Pass it those two functions you created:

$("button").toggle(function () {
    $("#sidebar").animate({ width: '0px' }, 250, function() {
       $(this).hide();
    });
    // the rest of your first animation sequence
}, function () {
    $("#sidebar").show().animate({
        width: "219px"
    }, 500);
    // the rest of your second animation sequence
});

You should also look into caching your selectors...


If you're using jQuery 1.9+, you'll have to keep your own flag:

$("button").click(function () {
    var toggle = $.data(this, 'clickToggle');

    if ( toggle ) {
        // your first animation sequence
    } else {
        // your second animation sequence
    }

    $.data(this, 'clickToggle', ! toggle);
});

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150010

You can set a flag to remember whether the element is currently on the "odd" or "even" click:

$("button").click(function() {
    var $this = $(this),
        flag = $this.data("clickflag");
    if (!flag) {
        // first code here
    } else {
        // second code here
    }
    $this.data("clickflag", !flag);
});

Demo: http://jsfiddle.net/KHLdr/

This uses jQuery's .data() method to store a boolean value against the clicked element.

Upvotes: 2

Related Questions