trascendency
trascendency

Reputation: 65

jQuery .animate(), problems with toggle

I'm relatively new to js and I'm trying to implement a simple .animate() feature in my portfolio. As you can see here, with the code I wrote the div called ribbon slides down perfectly, but it seems to ignore the "else" part of the script.

I know I'm probably doing a dumb mistake, but I can't seem to be able to work out anything better at the moment!

Sorry for my bad english, sucks to be Italian.

Upvotes: 0

Views: 462

Answers (2)

Jack
Jack

Reputation: 8941

Just taking what you had, simply put the if inside the click event.

http://jsfiddle.net/Rkqge/12/

$(document).ready(function() {
  $('#toggle').click(function() {
    if ($('#ribbon').css("margin-top") == "-300px") {
        $('#ribbon').animate({
            marginTop: "0px"
        }, 1700);
    } else {
        $('#ribbon').animate({
            marginTop: "-300px"
        }, 1700);
    }
 });
});

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78520

Just came up with a solution for another one like this a minute ago.

http://jsfiddle.net/HF5A5/

Basically you multiply the value by 1 or -1 and then toggle that value.

$(document).ready(function() {
    var direction = -1;
    $('#toggle').click(function() {
            direction -= direction * 2;
            $('#ribbon').animate({
                marginTop: "+=" + direction * 300 + "px"
            }, 1700);
            return false;
    });
});

or better yet: http://jsfiddle.net/HF5A5/1/

$(document).ready(function() {
    var direction = 1;
    $('#toggle').click(function() {
            $('#ribbon').animate({
                marginTop: "+=" + direction * 300 + "px"
            }, 1700, function(){
                $(this).stop();
                direction -= direction * 2;
            });
            return false;
    });
});

Upvotes: 3

Related Questions