Home >Web Front-end >CSS Tutorial >How to Create Resizable HTML Elements Using Pure JavaScript?
Creating Resizable HTML Elements with Pure JavaScript
Numerous libraries exist to enable element resizing, but for those seeking a pure JavaScript solution, the following steps can be utilized:
Here is a sample code snippet that implements this approach:
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); }
Keep in mind that this approach may not be compatible with all browsers, and Internet Explorer below version 9 is specifically known to have issues.
The above is the detailed content of How to Create Resizable HTML Elements Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!