Categories
JavaScript Answers

How to Get Browser Screen Width Using JavaScript Code?

Spread the love

Sometimes, we want to get the browser screen’s width with JavaScript code.

In this article, we’ll look at how to get a browser screen’s width with JavaScript code.

Using Properties of document.body or document.documentElement

The document.body is the JavaScript version of the HTML body element.

The document.documentElement is the JavaScript version of the HTML html element.

It has properties we need to get the width of the browser’s screen.

For instance, we can write:

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

console.log(getWidth())

to create a function to get the width of the broiwser’s screen.

document.body.scrollWidth is the full width of the content of the body element.

document.documentElement.scrollWidth is the full width of the content of the html element.

document.body.offsetWidth is the width of the body element t.including any borders, padding, and vertical scrollbars.

document.documentElement.offsetWidth is the width of the html element t.including any borders, padding, and vertical scrollbars.

document.documentElement.clientWidth is the inner width of an element in pixels. It includes padding but excludes borders, margins, and vertical scrollbars of the html element.

Each of them is in pixels.

Therefore, we can use the Math.max method to get the max value between each of them.

The function should return a number with the max between all those values.

Conclusion

We can use various properties of document.body or document.documentElement to get the width of the screen.

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 *