Home > Web Front-end > CSS Tutorial > How Can I Create Resizable HTML Elements Using Only Pure JavaScript?

How Can I Create Resizable HTML Elements Using Only Pure JavaScript?

Mary-Kate Olsen
Release: 2024-12-10 18:59:16
Original
953 people have browsed it

How Can I Create Resizable HTML Elements Using Only Pure JavaScript?

Creating Resizable HTML Elements with Pure JavaScript

Problem:

How can we make HTML elements like

or

resizable upon clicking, using only pure JavaScript?

Solution:

To make an HTML element resizable, we can create a custom resizer that manipulates its size:

// Element to make resizable
var p = document.querySelector('p');

// Initialize resizing on click
p.addEventListener('click', function() {

    // Remove click event listener and append resizer
    p.removeEventListener('click', init, false);
    p.className += ' resizable';

    var resizer = document.createElement('div');
    resizer.className = 'resizer';
    p.appendChild(resizer);

    // Attach mouse event listeners for resizing
    resizer.addEventListener('mousedown', initDrag, false);
});
Copy after login

Resizing Functionality:

We track mouse movement and adjust the element's size:

// Store initial values and mouse coordinates
var startX, startY, startWidth, startHeight;

function initDrag(e) {
    startX = e.clientX;
    startY = e.clientY;
    startWidth = parseInt(window.getComputedStyle(p).width, 10);
    startHeight = parseInt(window.getComputedStyle(p).height, 10);
    
    // Listen for mouse movement and update element's dimensions
    document.documentElement.addEventListener('mousemove', doDrag, false);
    document.documentElement.addEventListener('mouseup', stopDrag, false);
}

function doDrag(e) {
    p.style.width = (startWidth + e.clientX - startX) + 'px';
    p.style.height = (startHeight + e.clientY - startY) + 'px';
}

function stopDrag(e) {
    // Remove mouse event listeners
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Copy after login

The above is the detailed content of How Can I Create Resizable HTML Elements Using Only Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template