DEV Community

artydev
artydev

Posted on • Updated on

Using arrows to move a DOM element

I needed a simple way to move a DIV, but didn't want to use any external animation library.

You can test it here AnimDiv

<html lang="de">
  <head>
    <meta charset="utf-8" />
    <title>title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://efpage.de/DML/DML_homepage/lib/DML-min.js"></script>
  </head>
  <body>
    <script>
      const cssDiv = `
         top:0;
         position:absolute;
         width:100px;
         height:100px;

         background:red`;

      const cssApp = `
         margin:50px;
         position:relative;
         background:blue;
         height:66vh`;

      print(
        "<h1 style='text-align:center'>Use arrows to move the red square</h1>"
      );

      let info = div("");
      info.style.textAlign = "center";

      let app = div("", cssApp);

      selectBase(app);
      const square = div("", cssDiv);
      unselectBase();

      let keydown = false;

      function sleep() {
        return new Promise((r) => {
          setTimeout(r, 0);
        });
      }

      function log() {
        square.innerHTML = "";
        selectBase(square);
        print(`
               <div style='padding:10px;padding-top:25%'>
                 <div>Left : ${square.offsetLeft}</div>
                 <div>Top : ${square.offsetTop}</div>
               </div>
             `);
        unselectBase();
      }

      document.onkeydown = function (e) {
        e.preventDefault();
        if (e.repeat) return;
        keydown = true;
        switch (event.key) {
          case "ArrowLeft":
            move(square, "left", null);
            break;
          case "ArrowRight":
            move(square, "right", null);
            break;
          case "ArrowUp":
            move(square, null, "up");
            break;
          case "ArrowDown":
            move(square, "null", "down");
            break;
        }
      };

      document.onkeyup = function (e) {
        if (e.repeat) return;
        keydown = false;
      };

      function move(el, rl, ud) {
        const RIGHT = 1;
        const LEFT = -1;
        const UP = -1;
        const DOWN = 1;

        // move right or left
        let moveRL = async (dir) => {
          while (keydown) {
            await sleep();
            log();
            el.style.left = `${el.offsetLeft + dir}px`;
          }
        };

        // move up or down
        let moveUD = async (dir) => {
          while (keydown) {
            await sleep();
            log();
            el.style.top = `${el.offsetTop + dir}px`;
          }
        };

        if (rl == "right") moveRL(RIGHT);
        if (rl == "left") moveRL(LEFT);
        if (ud == "up") moveUD(UP);
        if (ud == "down") moveUD(DOWN);
      }

      log();
    </script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)