Categories
JavaScript Answers

How to get browser width using JavaScript?

Spread the love

To get browser width using JavaScript, we can get the max of a few values.

For instance, we write

const getWidth = () => {
  return Math.max(
    document.body.scrollWidth,
    document.documentElement.scrollWidth,
    document.body.offsetWidth,
    document.documentElement.offsetWidth,
    document.documentElement.clientWidth
  );
};

to define the getWidth function.

In it, we call Math.max to get the max of document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, and document.documentElement.clientWidth to get the width of the browser

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 *