Reputation: 71
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
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;
});
Upvotes: 1
Reputation: 460
You have toggleState variable inside function you need to move it outside.
Upvotes: 0