const stepSize = 100; const main = document.querySelector('main'); const draggables = document.querySelectorAll(".draggable"); const randomStarts = document.querySelectorAll(".randomStart"); var zIndex = 2; activateDraggables(); /** * * @param {number} n * @returns {number} */ function stepedSize(n) { return stepSize * Math.round(n / stepSize); } function move(e) { e.preventDefault(); let target = e.target; target.style['z-index'] = zIndex; zIndex++; target.moving = true; target.setAttribute('data-moving', '1'); target.oldX = e.clientX; target.oldY = e.clientY; target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1; target.oldTop = window.getComputedStyle(target).getPropertyValue('top').split('px')[0] * 1; document.addEventListener('mousemove', drag); function drag(event) { event.preventDefault(); if (!target.moving) { return; } target.distX = event.clientX - target.oldX; target.distY = event.clientY - target.oldY; newLeft = target.oldLeft + target.distX; newTop = target.oldTop + target.distY; target.style.left = stepedSize(newLeft) + "px"; target.style.top = stepedSize(newTop) + "px"; } function endDrag() { target.moving = false; target.setAttribute('data-moving', '0'); } document.addEventListener('mouseup', endDrag) } function activateDraggables() { for (var draggable of draggables) { draggable.addEventListener('mousedown', move); } } function randomizeDragables() { maxX = main.offsetWidth - 150; maxY = main.offsetHeight - 150; for (var randomStart of randomStarts) { randX = Math.floor(Math.random() * maxX); randY = Math.floor(Math.random() * maxY); randomStart.style.left = randX + "px"; randomStart.style.top = randY + "px"; } } document.addEventListener("DOMContentLoaded", randomizeDragables);