JSFiddle - React, Tailwind, and code Playground

by davehawkins

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />

    <title>Session Code</title>

    <script src="Animation.js"></script>

    <style>
      body {
        margin: 0;
        background-color: lightgray;
      }
      div {
        background-color: crimson;

        width: 30px;
        height: 30px;

        border-radius: 3px;

        position: absolute;

        top: 100px;
      }
    </style>
  </head>

  <body onload="onLoad()">
    <div id="obj_1"></div>
  </body>
</html>

JavaScript

let theDiv = null;
let xPos = 0;
let viewportWidth = window.innerWidth;
let goLeft = viewportWidth;

function onLoad() {
  theDiv = document.getElementById("obj_1");
  setInterval(onTick, 10);
}

function onTick() {
  if (xPos < viewportWidth) {
    theDiv.style.left = xPos + "px";
    xPos = xPos + 1;
    goLeft = viewportWidth;
  }
  if (xPos == viewportWidth) {
    theDiv.style.left = goLeft + "px";
    goLeft = goLeft - 1;
  }
  if (goLeft < 0) {
    goLeft = 0;
    xPos = 0;
    theDiv.style.left = xPos + "px";
    xPos = xPos + 1;
  }
}