Categories
JavaScript Answers

How to catch browser’s zoom event in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *