JSFiddle - React, Tailwind, and code Playground
HTML
<div id="desktop" onmousedown="initRect(event);">
`Click and drag inside this div
<div id="userBox"></div>
</div>
CSS
#desktop {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px;
position: absolute;
background-color: blue;
color: whitesmoke;
}
#userBox {
background-color: yellow;
position: absolute;
}
JavaScript
// The resizable box
var clientBox = document.getElementById("userBox");
var startX, startY, currentX, curentY;
function initRect(event) {
startX = event.clientX;
startY = event.clientY;
window.addEventListener("mousemove", drawRect);
window.addEventListener("mouseup", dstryRect);
}
function drawRect(event) {
var width = event.clientX-startX;
var height = event.clientY-startY;
var x = startX;
var y = startY;
if (width < 0) {
x = startX + width;
width=-width;
}
if (height < 0) {
y = startY + height;
height = -height;
}
clientBox.style.display = "block"; // Hideen until click detected
clientBox.style.top = y + "px";
clientBox.style.left = x + "px";
clientBox.style.width = width + "px";
clientBox.style.height = height + "px";
}
function dstryRect() {
window.removeEventListener("mousemove", drawRect);
window.removeEventListener("mouseup", dstryRect);
clientBox.style.display = "none";
clientBox.style.height = "0px";
clientBox.style.width = "0px";
}