How to make HTML elements resizable using pure JavaScript?

You can make HTML elements resizable using JavaScript by implementing functionality that captures mouse events and adjusts the size of the element accordingly.

To do this we can write:

HTML:

<div id="resizable" style="width: 200px; height: 200px; border: 1px solid black;">
    <!-- Content goes here -->
</div>

JavaScript:

<script>
    const resizableElement = document.getElementById('resizable');
    let isResizing = false;
    let initialX;
    let initialY;
    let initialWidth;
    let initialHeight;

    resizableElement.addEventListener('mousedown', (e) => {
        isResizing = true;
        initialX = e.clientX;
        initialY = e.clientY;
        initialWidth = parseInt(document.defaultView.getComputedStyle(resizableElement).width, 10);
        initialHeight = parseInt(document.defaultView.getComputedStyle(resizableElement).height, 10);
        document.addEventListener('mousemove', resizeElement);
        document.addEventListener('mouseup', stopResize);
    });

    function resizeElement(e) {
        if (isResizing) {
            const width = initialWidth + (e.clientX - initialX);
            const height = initialHeight + (e.clientY - initialY);
            resizableElement.style.width = `${width}px`;
            resizableElement.style.height = `${height}px`;
        }
    }

    function stopResize() {
        isResizing = false;
        document.removeEventListener('mousemove', resizeElement);
        document.removeEventListener('mouseup', stopResize);
    }
</script>

In this script, we start resizing when the user clicks on the element (mousedown event).

As the user moves the mouse (mousemove event), we calculate the change in mouse position and adjust the size of the element accordingly.

When the user releases the mouse button (mouseup event), resizing stops.

You can customize this code further to suit your specific requirements, such as constraining the minimum and maximum size of the element or adding resize handles.