Get the size of the screen, current web page and browser window
Eager to get the answers, huh? Let's dive in!
We are capturing screen, web page, and browser window sizes in JavaScript:
- Screen: Snag the full screen dimensions with
screen.width
andscreen.height
.
- Web page: Fetch the total scrollable content size with
document.documentElement.scrollWidth
anddocument.documentElement.scrollHeight
.
- Browser window: Get your viewport's dimensions excluding the scrollbars using
window.innerWidth
andwindow.innerHeight
.
The viewport size also minus the scrollbars can be gotten using document.documentElement.clientWidth
and document.documentElement.clientHeight
.
Coding for all — cross-browser compatibility
If you're the Indiana Jones of the developer world and you want your code to work in the mysterious jungles of all web browsers, here's the gist:
- For browser window dimensions, be the browser's best friend by using:
We're using the logical OR (||
). What it does? Ensures a safety net across different browsers.
jQuery to the rescue
Already using jQuery? Let's simplify:
- Browser window: Let jQuery work its charm:
- Web page: Similarly, bandwidth of page dimensions in jQuery language:
Screen real estate
Let's not ignore the stuff around your app:
- When you need available display area (because taskbars need space too):
It's a mobile world!
Responsive Techniques
Are you ready for mobile? Here's how to get responsively creative:
- Wave hello to relative units like
vw
(viewport width) andvh
(viewport height) in CSS for layout fluidity. - Throw in media queries to adapt styles based on the viewport size.
Mobile Specific Considerations
- Mind the viewport meta tag. Mobile browsers read it like their morning newspaper. Very informative, the
<meta name="viewport" content="width=device-width, initial-scale=1">
. - Be aware of virtual keyboards on mobile. They pop up and shake things. Yes, they can change viewport dimensions.
Dealing with browser quirks
The issue of scrollbars
Be careful when you're using window.innerWidth
and window.innerHeight
because these dimensions include our good friends, scrollbars. On the other hand, clientWidth
and clientHeight
usher them out. It's an open secret for a good layout.
Ensuring reliability
Quality check? Bring it on! Here's how to get reliable:
- Keep testing around. Rule multiple browsers, their legacy versions if your audience comes visiting from the past.
- Welcome a library like jQuery on board that takes care of cross-browser oddities.
- Stay updated. Pledge loyalty to caniuse.com, your guide to see browser support for various magical spells you cast with properties and features.
Was this article helpful?