Creating Resizable HTML Elements with Pure JavaScript
Problem:
How can we make HTML elements like
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); });
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); }
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!