-1

So I am having a problem with something that I think should be very simple.

I coded this example for simplicity's sake: I first noticed the problem in a larger body of code. However the issue still persists here.

<!DOCTYPE html>
<html>
<head>
<style>
#test
{
    height: 300px;
    width: 300px;
    background: blue;
    position:absolute;
    top: 0px;
    left: 0px;
}

</style>
</head>
<body>
<div id="test"></div>
<script src='jquery-1.10.2.min.js'>
</script>
<script>
var isClicked = false;
$(document).ready(function(){
    $('#test').click(function(){
        isClicked = true;
    });
    if (isClicked == true)
    {
        $('#test').animate({top:'200px'});
    }
});
</script>
</body>
</html>

The animation is not playing... obviously the same task could be accomplished in an easier way, but I still don't understand why the variable is not working. Probably just a stupid typo - but maybe not.

Thanks for the help!

3
  • 2
    You need to put the code with the if condition inside the click handler....? By the way what are you trying to achieve with the isClicked flag? $('#test').click(function(){ if (isClicked) { $(this).animate({top:'200px'}); } isClicked = !isClicked; }); Commented Nov 11, 2013 at 20:59
  • At the time of evaluating if isClicked (==true), isClicked isn't set. The code doesn't know it yet. Commented Nov 11, 2013 at 21:00
  • When you click, you just set the variable isClicked to true and nothing else. Put that if (...) {...} inside the function of the click. Commented Nov 11, 2013 at 21:00

2 Answers 2

4

Your test of isClicked is performed at dom ready, and at that point, you haven't clicked yet.

You should move the code in the click handler function.

Sign up to request clarification or add additional context in comments.

Comments

2

When the DOM is loaded, isClicked will have the value 'false'. Since the value is false, the animation will not occur. Change your JS in something like this:

$(document).ready(function () {
    var isClicked = false;
    $('#test').on('click', function (event) {
        isClicked = !isClicked;
        if (isClicked) {
            $(this).animate({top: '200px'});
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.