Sure, here’s how I would approach writing the article:
let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
In the code above, the window width is derived from three possible values representing the width of the viewport in pixels excluding the scroll bar.
Examining the Steps
In step one, we declare the variable “windowWidth” that will receive the sizes.
In step two, window.innerWidth is the width of the window’s content area including the vertical scrollbar (if it is visible). If this property is accessible, its value is stored in our variable.
let windowWidth = window.innerWidth;
If the window.innerWidth is undefined, we move to step three. document.documentElement.clientWidth fetches the interior width of the root element, providing a value in pixels.
let windowWidth = document.documentElement.clientWidth;
If document.documentElement.clientWidth is not defined, then as the last resort, the code will fetch the width of the body tag using document.body.clientWidth.
let windowWidth = document.body.clientWidth;
Related Libraries and Functions
For more complex applications or for opportunities to simplify the process of getting window sizes, some developers opt for library functions like jQuery’s $(window).width() function. This does add additional complexity to a project by including a whole library for this single feature, so it’s typically a better fit for larger projects where the library is used elsewhere.
Utilizing the Window Width in Responsive Design