Vlad Pintea
Vlad Pintea

Reputation: 71

Toggle function won't work

I have this div (in the shape of a block), which I want to move right and left by clicking on it. The idea is that the first toggle action works (meaning the block takes 250px of space from the left side) but won't move to the left after I click on it again.

$(document).ready(function()
{

    $("#block1").click(function()
    {
        var toggleState = true;
        if (toggleState)
        {
            $("#block1").animate({left: '250px'});
        }
        else
        {
            $("#block1").animate({left: '250px'});
        }
        toggleState = !toggleState;
    });
});

Upvotes: 0

Views: 40

Answers (2)

isherwood
isherwood

Reputation: 61124

You need to define toggleState outside the click function, otherwise its value is constantly overwritten. I've also defined the variable with a null value and changed the true condition left value, but neither of those were your primary issue.

var toggleState;

$("#block1").click(function() {
    if (toggleState) {
        $("#block1").animate({
            left: '10px'
        });
    } else {
        $("#block1").animate({
            left: '250px'
        });
    }
    toggleState = !toggleState;
});

Demo

Upvotes: 1

Kousi
Kousi

Reputation: 460

You have toggleState variable inside function you need to move it outside.

Upvotes: 0

Related Questions