monk monk - 4 years ago 323
HTML Question

How to make HTML element resizable using pure javascript?

i was wondering how we can make a HTML element like div or p tag element re-sizable when clicked using pure JavaScript not the jQuery library or any other library.

Answer Source

I really recommend using some sort of library, but you asked for it, you get it:

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';
    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) { = (startWidth + e.clientX - startX) + 'px'; = (startHeight + e.clientY - startY) + 'px';

function stopDrag(e) {
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);


Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download