How to use . toggle() to exchange animations

Asked

Viewed 178 times

3

I’m trying to alternate the animation of a div using .toggle(), but this div, which is the first gray ball, simply disappears after I click the button (orange ball), instead of returning to its initial position.

function main() {
    $('.mainBtn').click(function(){
        console.log("bolaxa");
        $('#btn1').toggle(
            function () {
                $(this).animate({left:'250px'}, 300);
            },
            function () {
                $(this).animate({right:'250px'}, 300);
            }

        );
    });
}

$(document).ready(main);

Here is the Jsfiddle: https://jsfiddle.net/s7q8qt0u/.
How can I get the ball back to where it started?

Grateful!

1 answer

4


That’s because you’re adding 250px positive in the second .animate() that makes the animation alternate, while you should make the animation come back to left:'0' instead, which is its initial place, not to 250px positive.

$('.mainBtn').click(function(){
    $('#btn1').toggle(function () {
            $(this).animate({left:'250px'}, 300);
        },
        function () {
            $(this).animate({left:'0'}, 300); // Aqui volta para o Zero, lugar inicial
        }
    );
});

Here’s an online example: https://jsfiddle.net/s9zkhw7p/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.