JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<button onclick="handleUndo()">undo</button>
<button onclick="handleRedo()">redo</button>
<h2>Click anywhere on the screen below to create a dot.</h2>
<div id="app" class="App"></div>
<div id="output"></div>
<script src="script.js"></script>

CSS

.App {
  position: relative;
  height: 100vh;
  border: 1px solid black;
}

.point {
  position: absolute;
  width: 5px;
  height: 5px;
  background-color: black;
  border-radius: 50%;
}

JavaScript

const point = [];
const undo = [];

function handleClick(e) {
  const { clientX, clientY } = e;
  point.push({ x: clientX, y: clientY });
  renderPoints();
}

function handleUndo() {
  if (!point.length) return;
  const poppedVal = point.pop();
  undo.push(poppedVal);
  renderPoints();
}

function handleRedo() {
  if (!undo.length) return;
  const poppedVal = undo.pop();
  point.push(poppedVal);
  renderPoints();
}

function renderPoints() {
  const app = document.getElementById("app");
  app.innerHTML = point
    .map((val, index) => `<div class="point" style="left:${val.x - 11}px; top:${val.y - 101}px;"></div>`)
    .join("");

  const output = document.getElementById("output");
  output.innerHTML = undo.length
    ? undo.map((val, index) => `<p key=${index}>${val.x}, ${val.y}</p>`).join("")
    : "nothing to pop";
}

document.getElementById("app").addEventListener("click", handleClick);