Sometimes, we want to catch browser’s zoom event in JavaScript.
In this article, we’ll look at how to catch browser’s zoom event in JavaScript.
How to catch browser’s zoom event in JavaScript?
To catch browser’s zoom event in JavaScript, we watch the resize event.
For instance, we write
const getSizes = () => {
const body = document.body;
body.width = window.innerWidth;
body.height = window.innerHeight;
console.log(body.width, body.height);
};
getSizes();
window.addEventListener("resize", getSizes, false);
to call addEventListener
to listen for the resize event.
getSizes
runs when we zoom in and out since the width and height in pixels will change.
Then we get the width and height of the window with innerWidth
and innerHeight
.
Conclusion
To catch browser’s zoom event in JavaScript, we watch the resize event.