Creating Resizable HTML Elements Using Vanilla JavaScript
The task of making HTML elements, such as
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); }
This code adds a 'resizable' class to the target element and appends an additional
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!