Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  75] [ 5]  / answers: 1 / hits: 199631  / 13 Years ago, sun, january 22, 2012, 12:00:00

I was wondering how we can make a HTML element like <div> or <p> tag element resizable when clicked using pure JavaScript, not the jQuery library or any other library.


More From » html

 Answers
19

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';
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);
}


Demo



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


[#87872] Friday, January 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;