<div id="resizeMe" class="resizable">Resize me</div>
<div id="resizeMe" class="resizable">Resize me<div class="resizer resizer-r"></div><div class="resizer resizer-b"></div></div>
.resizable {position: relative;}.resizer {/* All resizers are positioned absolutely inside the element */position: absolute;}/* Placed at the right side */.resizer-r {cursor: col-resize;height: 100%;right: 0;top: 0;width: 5px;}/* Placed at the bottom side */.resizer-b {bottom: 0;cursor: row-resize;height: 5px;left: 0;width: 100%;}
mousedown
on the resizers: Track the current position of mouse and dimension of the original elementmousemove
on document
: Calculate how far the mouse has been moved, and adjust the dimension of the elementmouseup
on document
: Remove the event handlers of document
// Query the elementconst ele = document.getElementById('resizeMe');// The current position of mouselet x = 0;let y = 0;// The dimension of the elementlet w = 0;let h = 0;// Handle the mousedown event// that's triggered when user drags the resizerconst mouseDownHandler = function (e) {// Get the current mouse positionx = e.clientX;y = e.clientY;// Calculate the dimension of elementconst styles = window.getComputedStyle(ele);w = parseInt(styles.width, 10);h = parseInt(styles.height, 10);// Attach the listeners to `document`document.addEventListener('mousemove', mouseMoveHandler);document.addEventListener('mouseup', mouseUpHandler);};const mouseMoveHandler = function (e) {// How far the mouse has been movedconst dx = e.clientX - x;const dy = e.clientY - y;// Adjust the dimension of elementele.style.width = `${w + dx}px`;ele.style.height = `${h + dy}px`;};const mouseUpHandler = function () {// Remove the handlers of `mousemove` and `mouseup`document.removeEventListener('mousemove', mouseMoveHandler);document.removeEventListener('mouseup', mouseUpHandler);};
mousedown
event handler to all the resizers:// Query all resizersconst resizers = ele.querySelectorAll('.resizer');// Loop over them[].forEach.call(resizers, function (resizer) {resizer.addEventListener('mousedown', mouseDownHandler);});