JSFiddle - React, Tailwind, and code Playground

by Константин Дралюк

HTML

<div id="p">
  <div id="s"></div>
</div>

CSS

body {
  margin: 0;
}

#p {
  background: #ccc;
  width: 400px;
  height: 400px;
}

#s {
  width: 100px;
  height: 100px;
  background: #000;
}

#r {
  font-size: 18px;
}

JavaScript

var slide = s;
var container = p;

var state = {
	draggable: false,
  x: 0,
  y: 0,
  lastX: 0,
  lastY: 0,
  maxX: 0,
  maxY: 0,
  scrollX: 0,
  scrollY: 0,
}

var updateXY = function(e) {
  state.x = e.clientX - state.lastX;
  state.y = e.clientY - state.lastY;
},
updateLastXY = function(e) {
  state.lastX = e.clientX - state.x;
  state.lastY = e.clientY - state.y;
},
updateScrollXY = function(e) {
  state.scrollX = state.lastX -= (((e.wheelDeltaX > 0) - (e.wheelDeltaX < 0)) || +e.wheelDeltaX) * state.maxX;
  state.scrollY = state.lastY -= (((e.wheelDeltaY > 0) - (e.wheelDeltaY < 0)) || +e.wheelDeltaY) * state.maxY;
},
updateMaxXY = function() {
  state.maxX = container.offsetWidth - slide.offsetWidth;
  state.maxY = container.offsetHeight - slide.offsetHeight;
},
fitParent = function() {
	updateMaxXY();
  
  if (state.lastX < 0) state.lastX = 0;
  if (state.lastY < 0) state.lastY = 0;
  if (state.lastX > state.maxX) state.lastX = state.maxX;
  if (state.lastY > state.maxY) state.lastY = state.maxY;
  
  if (state.scrollX < 0) state.scrollX = 0;
  if (state.scrollY < 0) state.scrollY = 0;
  if (state.scrollX > state.maxX) state.scrollX = state.maxX;
  if (state.scrollY > state.maxY) state.scrollY = state.maxY;
},
holdOn = function(e) {
	state.draggable = true;
  updateXY(e);
},
holdOff = function(e) {
	state.draggable = false;
  updateXY(e);
},
move = function(e) {
	if (state.draggable) {
  	updateLastXY(e);
    fitParent();
    slide.style.transform = 'translateX('+(state.lastX)+'px) translateY('+(state.lastY)+'px)';
	slide.style.transition = '';
  }
},
scroll = function(e) {
	updateScrollXY(e);
  fitParent();
	slide.style.transform = 'translateX('+(state.scrollX)+'px) translateY('+(state.scrollY)+'px)';
	slide.style.transition = '.5s ease';
};

slide.onmousedown = holdOn;
document.onmousemove = move;
document.onmouseup = holdOff;

container.onmousewheel = scroll;

window.onresize = fitParent;

// TODO
// Refactor, add touch, add events - start, process,...