Matrix test

by Sam Fereday

HTML

<div class="inner">
  <div class="shape">
  </div>
</div>

CSS

html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.inner {
  width: 1600px;
  height: 1600px;
  position: absolute;
  left: 0;
  top: 0;
  background: url('https://www.publicdomainpictures.net/pictures/90000/velka/lime-and-beige-checkerboard-pattern.jpg');
}

.shape {
  width: 320px;
  height: 320px;
  position: absolute;
  left: 500px;
  top: 500px;
  background: #333;
}

JavaScript

const dragElement = (el) => {

  let dragging = false;

  let clientX = 0,
    clientY = 0;

  el.addEventListener('mousedown', (e) => {
    clientX = e.clientX;
    clientY = e.clientY;
    dragging = true;
  });

  document.addEventListener('mousemove', (e) => {
    if (!dragging) {
      return;
    }

    let x = clientX - e.clientX;
    let y = clientY - e.clientY;

    clientX = e.clientX;
    clientY = e.clientY;

    el.style.top = el.offsetTop - y > 0 || Math.abs(el.offsetTop - y) > document.body.clientHeight ? el.offsetTop + "px" : (el.offsetTop - y) + "px";
    el.style.left = el.offsetLeft - x > 0 || Math.abs(el.offsetLeft - x) > document.body.clientWidth ? el.offsetLeft + "px" : (el.offsetLeft - x) + "px";

  });

  document.addEventListener('mouseup', () => {
    dragging = false;
  });
}

const draggableBit = document.querySelector('.inner');
dragElement(draggableBit);