jQuery flag animation on click

I'm trying to make a program where there's a flag next to a pole. It starts out at the bottom of the pole, and when the user clicks on it, it moves to the top of the pole. When it's at the top, if the user clicks on it again, it moves to the bottom. So I am trying to make that flag effect. But right now with what I have the first part's working, where it moves up. But the moving down part is not. Can someone help? Thanks.

<!DOCTYPE html>
<html>
    <head>
        <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">. 
        </script>
   </head>
  <body>
       <img src = "https://upload.wikimedia.org/wikipedia/en/thumb/6/6c/Us_flag_large_38_stars.png/1200px-Us_flag_large_38_stars.png" id = "flag" width = "200px" height = "140px">
       <div id = "pole"></div>
    
     <script>
        //booleans
        var reachedTop = false;
        var reachedBottom = true;
        
        //initial positioning
        $("#pole").width(10);
        $("#pole").height($(document).height());
        $("#pole").css("background-color", "gray");
        $("#pole").css({left: $(document).width() * 5/12});
        $("#pole").css("position", "absolute");
        
        $("#flag").css("position", "absolute");
        $("#flag").css({left: $("#pole").position().left, top: $(document).height()/3});
        
        //animations on clicks
        if (reachedBottom && reachedTop == false){
            $("#flag").click(function(){
              
                $("#flag").animate({top: $("#pole").position().top});
                if ($("#flag").position().top == $("#pole").position().top){
                    reachedTop = true;
                    reachedBottom = false;
                }
            });
        } else if (reachedTop && reachedBottom == false){
            $("#flag").click(function(){
                $("#flag").animate({top: $(document).height()/3});
                if ($("#flag").position().top == $(document).height()/3){
                    reachedTop = false;
                    reachedBottom = true;
                }
            });
        }
    </script>
</body>


Read more here: https://stackoverflow.com/questions/64960803/jquery-flag-animation-on-click

Content Attribution

This content was originally published by AdiBak at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: