JSFiddle - React, Tailwind, and code Playground

by Dominik Wilk

HTML

<body>
  <input type="textarea" id="area" disabled />
  <div class="rect" id="rect"></div>
  <div class="relative-rect" id="relative-rect"></div>
</body>

CSS

.rect {
  position: absolute;
  top: 100px;
  left: 100px;
  background-color: red;
  height: 50px;
  width: 50px;
}

.relative-rect {
  background-color: blue;
  height: 50px;
  width: 50px;
}

#area {
  position: fixed;
  right: 0;
  top: 0;
}

body {
  height: 500px;
}

JavaScript

document.getElementById('rect').addEventListener('click', printPosition)

document.getElementById('relative-rect').addEventListener('click', printPosition)

function getPosition(e) {
  var rect = e.target.getBoundingClientRect();
  alert(e.clientX)
  var x = e.clientX - rect.left;
  var y = e.clientY - rect.top;
  return {
    x,
    y
  }
}

function printPosition(e) {
  var position = getPosition(e);
  document.getElementById('area').value = 'X: ' + position.x + ' Y: ' + position.y;
}