Creating The Bucket Game

Creating The Bucket Game

In this project, I am making a game where balls or drops are falling and the user have to catch the falling object by moving a bucket left or right For movement of the bucket, I am thinking about using 2 buttons left and right. When the user press the left button bucket will move left and when right button is pressed bucket will move right. First I start on the logic part, which is how a user can move a bucket from its original position after pressing a button. For trial and error purposes I have created a simple static website with 1 button and one div element.

image.png

As the position of the box is a CSS property therefore I am thinking of changing this property by using document.getElementById()function followed by .style and CSS property which I have to change, in this case, it is position.

The next step is to create a function in JavaScript that can change these CSS properties when the button is being pressed.

function move(){
            document.getElementById("box").style.position="relative";
            document.getElementById("box").style.left="100px";
}

Also, I have edited the button tag and added the onclick function to it. <button id="btn" onclick="move()">Move</button>

Now whenever the button is pressed box shifts towards the right, but this occurs only once when again button is pressed nothing happens.

image.png

To solve this issue I have created a variable 'pos' which increases by some amount say '10' when the button is pressed and then new position values for the box element is 'pos+10' hence box shifts by 10Pixels whenever the button is pressed. I have also added a new variable which adds 'px' at the end of the new position value.

var pos=0;
function move(){
            pos=pos+10;
            var pos_string=pos+"px";
            document.getElementById("box").style.position="relative";
            document.getElementById("box").style.left=pos_string;%[%[Link]]
}

Here is the video from the tweet showing working of this code-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        #box{
            border: 10px solid red;
            height: 100px;
            width: 100px;
        }
    </style>
    <button id="btn" onclick="move()">Move</button>
    <div id="box"></div>
    <script>
        var pos=0;
        function move(){
            pos=pos+10;
            var pos_string=pos+"px";
            document.getElementById("box").style.position="relative";
            document.getElementById("box").style.left=pos_string;
        }
    </script>
</body>
</html>