How to Make HTML Element Resizable Using Pure JavaScript

How to make HTML element resizable using pure Javascript?

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).

I made a pure JS resizeable element, but the resizing element is not smooth. How do I make this more smooth?

@Harshal Carpenter, here's my snippet:

What I've done to your code is that:

1.Remove these lines, which prevents the image to become smaller after the resize it to larger previously.

if (newW < elem.originalW) {
elem.style.width = newW + 'px';
}

  1. Remove the this.onmouseout to prevent resizing stop when you leave your mouse from that circular handle. You might want to continue resizing because your mouse might move to fast before the circular knob do, which end up your mouse cursor exiting the circular knob.

  2. attach the mouse event listener to the div#imageBack instead of the div#content-resize, the same reason as above, you might want it to continue dragging even if the mouse leaves the div#content-resize.

var links = document.getElementById("imageLinks");links.onmousedown = function(e) {  var theSrc = e.target.dataset.src;  if (theSrc) {    str = "url(\"" + theSrc + "\");";    //Sorry for using this:    document.getElementById("imageBack").setAttribute("style", "background-image:" + str)  }}

var container = document.getElementById("imageBack");var resizer = document.getElementById("content-resize");container.onmousedown = resizableStart;
function resizableStart(e) { if(e.target == resizer){ var elem = document.getElementById("content"); elem.originalW = elem.clientWidth; this.onmousemove = resizableCheck; this.onmouseup = resizableEnd; }}
function resizableCheck(e) { var elem = document.getElementById("content"); if (elem.clientWidth === elem.originalW) { elem.originalX = e.clientX; this.onmousemove = resizableMove; }}
function resizableMove(e) { var elem = document.getElementById("content"); var newW = elem.originalW - e.clientX + elem.originalX; elem.style.width = newW + 'px';}
function resizableEnd() { this.onmousemove = this.onmouseout = this.onmouseup = null;}
html,body {  min-height: 100% !important;  height: 100%;}
.container { width: 100%; min-height: 100%; height: 100%;}
.images { width: 100%; min-height: 100% !important; height: 100%;}
#content { min-height: 100% !important; height: 100%; /*Change this to change width*/ width: 70%; resize: horizontal; float: right; position: relative; background: white;}
div { border: 1px solid black;}
span { border: 1px solid black; border-radius: 50%; position: absolute; top: calc(50% - 20px); left: -10px; cursor: pointer; height: 40px; width: 40px; display: inline-block; background: white;}
<div class='container'>  <div class='images' id="imageBack" style="background-image: url('http://data.whicdn.com/images/20948152/large.png')">
<div class='content' id="content"> <div id="imageLinks"> <a href="#" data-src='http://ichef.bbci.co.uk/news/660/cpsprodpb/1325A/production/_88762487_junk_food.jpg'>1</a> <a href="#" data-src='http://i.imgur.com/NhDejjN.jpg'>2</a> <a href="#" data-src='https://s-media-cache-ak0.pinimg.com/564x/80/40/9d/80409d8c06d21e0c0416a40c2176def3.jpg'>3</a> <a href="#" data-src='http://data.whicdn.com/images/20948152/large.png'>4</a> </div> <span id="content-resize"></span> </div> </div></div>

JS resizable div

You haven't consider the case where mouse move coordinates are less than the drawing start coordinates, I have modified the JS code a bit,

var clientBox = document.getElementById("userBox");
var startX, startY, currentX, curentY;

function initRect(event) {
startX = event.clientX;
startY = event.clientY;
window.addEventListener("mousemove", drawRect);
window.addEventListener("mouseup", dstryRect);

}

function drawRect(event) {
var width = event.clientX-startX;
var height = event.clientY-startY;
var x = startX;
var y = startY;
if (width < 0) {
x = startX + width;
width=-width;
}
if (height < 0) {
y = startY + height;
height = -height;
}
clientBox.style.display = "block"; // Hideen until click detected
clientBox.style.top = y + "px";
clientBox.style.left = x + "px";
clientBox.style.width = width + "px";
clientBox.style.height = height + "px";
}

function dstryRect() {
window.removeEventListener("mousemove", drawRect);
window.removeEventListener("mouseup", dstryRect);
clientBox.style.display = "none";
clientBox.style.height = "0px";
clientBox.style.width = "0px";
}

just update these chnages in JS file and you are done.
Here is the working fiddle
Thanks.

How resize a div height based on width with pure JavaScript

You need to find the current width of the element and then reset its height.

Here's a simple example of doing that. It is using offsetWidth to get the current width, but depending on your use case that may or may not be good enough. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.

// Function to set the height of an element proportional to its width
// el is the element we are interested in.
// ratio is the ratio of width to height that we want
function setHeight(el, ratio) {

// first we need to find out what the width of el currently is
const w = el.offsetWidth; //this will always return an integer
console.log(w);
el.style.height = (w * ratio) + 'px';

//note you could also investigate getBoundingClientRect().width for a more general case when there have been transformations
}
<div class="element" style="width: 200px; height: 200px; background-color: magenta;" onclick="setHeight(this, 600/300);">Click me</div>

How to make this resizable div, resizable from edges?

You cannot achieve this if you want to preserve the aspect ratio. So basically when you remove that option from the resizable, you can use the corners to drag on any direction as per your requirement and scale it across height and width.

$('.resizable').resizable({
//aspectRatio: true, //comment or remove this
handles: 'ne, se, sw, nw'
});

DEMO



Related Topics



Leave a reply



Submit