JavaScript Answers

How to make HTML elements resizable using pure JavaScript?

Spread the love

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:


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


    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);
   = `${width}px`;
   = `${height}px`;

    function stopResize() {
        isResizing = false;
        document.removeEventListener('mousemove', resizeElement);
        document.removeEventListener('mouseup', stopResize);

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *