JSFiddle - React, Tailwind, and code Playground
HTML
<ol>
<li>Drag horizontally</li>
<li>Release</li>
<li>Drag vertically</li>
<li>Relase</li>
<li>Press and hold</li>
</ol>
<div id="box"></div>
CSS
body {
font: 12px sans-serif;
}
#box {
width: 300px;
height: 300px;
border: 1px #000 solid;
text-align: center;
padding: 20px;
transition: 0.2s background-color;
cursor: pointer;
}
#box.waiting {
background-color: gray;
cursor: move;
}
#box.dragX {
background-color: red;
cursor: ew-resize;
}
#box.dragY {
background-color: green;
cursor: ns-resize;
}
#box.press {
background-color: yellow;
cursor: progress;
}
JavaScript
var mode = document.getElementById('mode');
var box = document.getElementById('box');
// State
var currentMode;
var mouseDownEvent;
var prop;
var pressTimeout;
box.addEventListener('mousedown', function (event) {
mouseDownEvent = event;
box.className = 'waiting';
box.innerHTML = 'waiting...';
pressTimeout = setTimeout(function() {
box.className = 'press';
prop = 'timeStamp';
box.innerHTML = '';
}, 1000);
});
document.body.addEventListener('mouseup', function () {
mouseDownEvent = null;
prop = null;
box.className = '';
box.innerHTML = '';
clearTimeout(pressTimeout);
});
box.addEventListener('mousemove', function (event) {
if (!mouseDownEvent) {
return;
}
event.preventDefault();
var deltaX = event.clientX - mouseDownEvent.clientX;
var deltaY = event.clientY - mouseDownEvent.clientY;
if (!prop) {
if (deltaX < -25 || deltaX > 25) {
box.className = 'dragX';
prop = 'clientX';
clearTimeout(pressTimeout);
} else if (deltaY < -25 || deltaY > 25) {
box.className = 'dragY';
prop = 'clientY';
clearTimeout(pressTimeout);
} else {
// not enough to change mode
}
} else {
var delta = event[prop] - mouseDownEvent[prop];
box.innerHTML = prop + ': ' + delta;
}
});