Sometimes, we want to make HTML element resizable using JavaScript.
In this article, we’ll look at how to make HTML element resizable using JavaScript.
How to make HTML element resizable using JavaScript?
To make HTML element resizable using JavaScript, we can listen to the mousemove
event.
For instance, we write
const div = document.querySelector(`div.before`);
const box = document.querySelector(`div.container`);
box.addEventListener(`mousemove`, (e) => {
const { offsetX, offsetY } = e;
div.style.width = offsetX + `px`;
});
to select the div we want to resize with
const div = document.querySelector(`div.before`);
Then we select its container with
const box = document.querySelector(`div.container`);
Next, we listen to the mousemove
event with addEventListener
.
In the event listener, we set the width
of the div
to the horizontal mouse position.
Conclusion
To make HTML element resizable using JavaScript, we can listen to the mousemove
event.