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

How Can I Make HTML Elements Resizable Using Only Vanilla JavaScript?

Mary-Kate Olsen
Release: 2024-12-08 07:51:15
Original
933 people have browsed it

How Can I Make HTML Elements Resizable Using Only Vanilla JavaScript?

Creating Resizable HTML Elements Using Vanilla JavaScript

The task of making HTML elements, such as

or

tags, resizable when clicked can be achieved without relying on external libraries like jQuery. Here's how you can accomplish this using pure JavaScript:

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

p.addEventListener('click', function init() {
    p.removeEventListener('click', init, false);
    p.className = p.className + ' resizable';
    var resizer = document.createElement('div');
    resizer.className = 'resizer';
    p.appendChild(resizer);
    resizer.addEventListener('mousedown', initDrag, false);
}, false);

var startX, startY, startWidth, startHeight;

function initDrag(e) {
   startX = e.clientX;
   startY = e.clientY;
   startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
   startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
   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) {
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Copy after login

This code adds a 'resizable' class to the target element and appends an additional

with class 'resizer' to the element. When the 'resizer' is clicked, the mouse drag and drop events are captured to dynamically adjust the width and height of the target element based on the mouse movements.

Keep in mind that this solution may not be compatible with all browsers. For a more robust implementation, consider using a JavaScript library dedicated to element resizing.

The above is the detailed content of How Can I Make HTML Elements Resizable Using Only Vanilla 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