Position element with coordinates

by ShaCP

HTML

<div class="reference">

</div>

CSS

.reference {
  position: absolute;
  top: 300px;
  left: 500px;
  height: 50px;
  width: 50px;
  background-color: lightcoral;
}

body {
  height: 200vh;
}

JavaScript

/* function createMoveableElement () {
var element = `<div class="moveable-element">move me</div>`

} */

function createMessageUnder(elem, html) {
  let message = document.createElement('div');
  message.style.cssText = "position:absolute; color: red";
	console.log(getCoords(elem));
  let coords = getCoords(elem);

  message.style.left = coords.left + "px";
  message.style.top = coords.bottom + "px";

  message.innerHTML = html;

  return message;
}

function getCoords(elem) {
  let box = elem.getBoundingClientRect();
  /* I need to add the page offset because the bounding rectangle
  coordinates are based on the viewport, not the page. So, for example,
  if the element is positioned to that its bottom is sitting at the top of
  the viewport, meaning it's scrolled out of view, then the coordinates
  of the bottomo would be 0, the start of the viewport. pageOffset gives you
  the amount of pixels the page has been scrolled
  */
  return {
    top: box.top + window.pageYOffset,
    right: box.right + window.pageXOffset,
    bottom: box.bottom + window.pageYOffset,
    left: box.left + window.pageXOffset
  };
}

document.body.appendChild(createMessageUnder(document.querySelector(".reference"), "hello"));