0

I created a program when we press a number pad, my robot will move to a location which I set. And when I press the enter key, the robot will move back to the start point. So when I press number pad "1" it move to the 1st location then "2" move to the second location, so on so for. And when I press the enter key, it moves back to the start location. But why after I press the enter key, I'm not able to move my robot to the other location by pressing the number pad?

Could someone help me with this coding?

The bottom is my coding for my program.

        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <meta http-equiv="X-UA-Compatible" content="ie=edge" />
            <title>Document</title>
            <style>
              body {
                height: 100%;
                width: 100%;
                background-image: url("TPHRG floorplan1.png");
                background-repeat: no-repeat;
                background-attachment: fixed;
                /* background-position: center; */
                background-size: 980px 400px, cover;
              }

              .robot_start_top {
                top: 280px;
                transition: top 2s;
              }

              .robot_start_left {
                position: fixed;
                left: 600px;
                transition: all 2s;
              }

              .robot_end_left {
                left: 570px;
              }

              .robot_end_top {
                top: 180px;
              }

              .robot1_start_left {
                position: fixed;
                left: 570px;
                transition: left 4s;
              }

              .robot1_end_left {
                left: 520px;
              }

              .robot2_start_left {
                position: fixed;
                left: 520px;
                transition: left 4s;
              }

              .robot2_end_left {
                left: 470px;
              }
              .robot3_start_left {
                position: fixed;
                left: 470px;
                transition: left 4s;
              }

              .robot3_end_left {
                left: 420px;
              }

              .robot3_start_right {
                position: fixed;
                left: 470px;
                transition: left 4s;
              }
              .robot3_start_down {
                position: fixed;
                left: 180px;
                transition: left 4s;
              }

              .robot3_end_down {
                top: 280px;
              }

              .robot3_end_right {
                left: 570px;
              }
            </style>
          </head>
          <body onkeydown="move(event)">
            <div class="robot_start_left robot_start_top" id="app">
              <img id="robot" style= width:30px; height:40px" src="https://i.pinimg.com/originals/4a/8d/3c/4a8d3c7d97e4b5bbf2d5d6f8c1dc57e8.jpg">
            </div>

            <script>
              var move = function(event) {
                if (event.keyCode === 97) {
                  const appDiv = document.getElementById("app");
                  setTimeout(function() {
                    appDiv.classList.add("robot_end_top");
                  }, 0);
                  setTimeout(function() {
                    appDiv.classList.add("robot_end_left");
                  }, 2000);
                }

                if (event.keyCode === 98) {
                  const appDiv = document.getElementById("app");
                  appDiv.classList.add("robot1_end_left");
                }

                if (event.keyCode === 99) {
                  const appDiv = document.getElementById("app");
                  appDiv.classList.add("robot2_end_left");
                }

                if (event.keyCode === 100) {
                  const appDiv = document.getElementById("app");
                  appDiv.classList.add("robot3_end_left");
                }

                  if (event.keyCode === 13) {
                    const appDiv = document.getElementById("app");
                    setTimeout(function() {
                      appDiv.classList.add("robot3_end_down");
                    }, 2000);
                    setTimeout(function() {
                      appDiv.classList.add("robot3_end_right");
                    }, 0);
                  }

              }
            </script>
          </body>
        </html>
  • 2
    Have you used your browser's debugger? – Dai Dec 20 '19 at 06:20
  • 2
    `event.keyCode` is [deprecated](https://stackoverflow.com/questions/35394937/keyboardevent-keycode-deprecated-what-does-this-mean-in-practice). You should use `event.key`. – Toastrackenigma Dec 20 '19 at 06:21
  • 1
    You'll probably want to manage some state and keep appending the distance to the absolute position in each vector. – Bryantee Dec 20 '19 at 06:26
  • 1
    Could you add your codes inside the `JavaScript/HTML/CSS snippet` by clicking on that button when you edit your post? This allows us to run your code more easily. Another alternative is by clicking `Ctrl+M` and place the relevant HTML/CSS/JS in the appropriate boxes. – Richard Dec 20 '19 at 06:32
  • Can you add double quotation to the style attribjute for the img element from style=width:30px; height:40px" to style="width:30px; height:40px" – Alan M Dec 20 '19 at 07:21

3 Answers3

1

As other contributors have pointed out the issue is that you don't remove the the classes which are added once you are done with them. For example:

  • Press 2; and the class robot1_end_left is added to the robot.
  • Press enter; and at the end the robot will have the classes robot1_end_left robot3_end_down robot3_end_right applied.
  • Now press 2 again; it will try to apply robot1_end_left again, but because you can't add the same class twice, the class list will just remain the same, resulting in no change to the robot - and thus the problem you are having.

While there are solutions for this (e.g. removing the classes when you are done with them), this then starts to make your program less and less flexible, and very delicate / easy to break. How do you know when to remove the right classes? What if the user presses the wrong key and the class gets removed prematurely? What if you only removed the classes when the enter key was pressed, but someone presses 1 2 1? There has to be a better way.


If you keep track of the position of your robot in variables, you can easily add / subtract numbers from those variables, and then set the robots position to the position stored in the variables via JavaScript.

For example:

let x = 0;
let y = 0;

function move(ev) {
    if      (ev.key == "Numpad 1") x -= 100;         // Move left
    else if (ev.key == "Numpad 2") y -= 100;         // Move up
    else if (ev.key == "Numpad 3") x += 100;         // Move right
    else if (ev.key == "Numpad 4") y += 100;         // Move down
    else if (ev.key == "Enter")    { x = 0; y = 0; } // Reset position
    let robot = document.getElementById("robot");
    robot.style.left = x + "px";
    robot.style.top  = y + "px";
}

This way, if the user presses 1 twice, the robot will move 200px to the left, if the user presses it again the new position of the robot will be 300px to the left, etc. Pressing enter will move the robot back to its starting position.

I know this is not the same as the code you initially started with, and obviously I do not know what you are trying to accomplish / what your actual desired outcome is, but I think that anything that involves "dynamic" movement like this will probably be way easier to implement this way.

Remember, you'll still need some CSS, e.g:

#robot {
    position: absolute;
    transition: left 1s linear, top 1s linear;
}
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
  • Hi, you bring out a very good point. But what I'm trying to get is, by pressing number 1 it will move to my 1st location when pressing number 2 it will move to the second location, so on so far. And when I press enter it will return to the starting position. So not sure if you could help me out. Thanks – Chiong Wilson Dec 20 '19 at 07:14
  • Instead of, say, `x -= 100` you could use something like I did for the reset, e.g. `{ x = 12; y = 65; }` – Toastrackenigma Dec 20 '19 at 07:17
0

After you click enter, the CSS class that takes precedence seems to be the 'start position' one. You'll want to clear all classes before setting the new class. Given the element id app, that would look like this: document.getElementById("app").removeAttribute("class");

I would add this at the very beginning of the move js function.

-1

Try writing IFEE function and run the event on the document or window e.g.

function move (event) {
   console.log('ola')
}
(function init() {
   window.onkeydown(move)
})();
Abhishek
  • 29
  • 6