JSFiddle - React, Tailwind, and code Playground

by ckissi

HTML

<div id="myDiv">
    <div id="resizeHandle"></div>
</div>

CSS

#myDiv {
    width: 200px;
    height: 200px;
    background-color: #f0f0f0;
    position: absolute;
    top: 50px;
    left: 50px;
    cursor: move;
    border: 1px solid #ccc;
    user-select: none;
}
#resizeHandle {
    width: 10px;
    height: 10px;
    background-color: #333;
    position: absolute;
    right: 0;
    bottom: 0;
    cursor: se-resize;
}

JavaScript

const div = document.getElementById('myDiv');
const resizeHandle = document.getElementById('resizeHandle');
let isDragging = false;
let isResizing = false;
let startX, startY, startWidth, startHeight;

div.addEventListener('mousedown', dragStart);
resizeHandle.addEventListener('mousedown', resizeStart);
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', dragEnd);

function dragStart(e) {
    if (e.target === resizeHandle) return;
    isDragging = true;
    startX = e.clientX - div.offsetLeft;
    startY = e.clientY - div.offsetTop;
}

function resizeStart(e) {
    isResizing = true;
    startX = e.clientX;
    startY = e.clientY;
    startWidth = parseInt(getComputedStyle(div).width, 10);
    startHeight = parseInt(getComputedStyle(div).height, 10);
    e.stopPropagation();
}

function drag(e) {
    if (isDragging) {
        div.style.left = e.clientX - startX + 'px';
        div.style.top = e.clientY - startY + 'px';
    } else if (isResizing) {
        const width = startWidth + (e.clientX - startX);
        const height = startHeight + (e.clientY - startY);
        div.style.width = width + 'px';
        div.style.height = height + 'px';
    }
}

function dragEnd() {
    isDragging = false;
    isResizing = false;
}