Robert Hovhannisyan
Robert Hovhannisyan

Reputation: 3335

Add multiple classes to dom element one by one js

I want to add 2 classes to my div with an event listener, but I want it to add one list, update the DOM, and add the second class

I need to move the div with the id app to the top and then to the left when the user clicks the key 1, but it goes up and left at the same time.

<!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 1s;
      }

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

      .robot_end_left {
        left: 500px;
      }

      .robot_end_top {
        top: 180px;
      }

      .robot1_start_left {
        position: fixed;
        left: 600px;
        transition: left 1s;
      }

      .robot1_end_left {
        left: 400px;
      }
    </style>
  </head>
  <body onkeydown="move(event)">
    <div class="robot_start_left robot_start_top" id="app">
      <img id="robot" style="width:30px; height:40px" />
    </div>

    <script>
      let count = 0;
      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");
          }, 0);
        }

        if (event.keyCode === 98) {
          const appDiv = document.getElementById("app");
          appDiv.classList.add("robot1_end_left");
        }
      };
    </script>
  </body>
</html>

but in this way, it adds all 2 classes at once.

Here is the whole code in CodeSandBox

Upvotes: 2

Views: 367

Answers (1)

Pointy
Pointy

Reputation: 413702

Browsers will generally let JavaScript code like yours do a burst of DOM updates without doing anything visually. They'll wait until the script exits (like an event handler) or until something in the script requires that the browser do the visual update before it can provide an answer.

In your case, the simplest thing to do is defer the addition of the "second" class for some fractions of a second; exactly how long depends on what you want it to look like. The way you'd do that would be something like

  setTimeout(() => { appDiv.classList.add("robot_end_left") }, 500);

That 500 means to wait 500 milliseconds before adding the second class.

Upvotes: 1

Related Questions