How to Get Window Size in JavaScript: Simple Methods
You can get the window size in JavaScript using
window.innerWidth for width and window.innerHeight for height. These properties give the size of the visible area inside the browser window.Syntax
Use window.innerWidth to get the width of the browser window's content area in pixels. Use window.innerHeight to get the height. These values update when the window is resized.
javascript
const width = window.innerWidth; const height = window.innerHeight;
Example
This example shows how to get and display the current window size in the browser console and update it when the window is resized.
javascript
function showWindowSize() { const width = window.innerWidth; const height = window.innerHeight; console.log(`Width: ${width}px, Height: ${height}px`); } // Show size initially showWindowSize(); // Update size on window resize window.addEventListener('resize', showWindowSize);
Output
Width: 1024px, Height: 768px
// (Output updates on resize with new values)
Common Pitfalls
Some developers try to use document.body.clientWidth or document.documentElement.clientWidth which may not always reflect the visible window size accurately, especially with scrollbars or doctype differences. Also, remember to listen for the resize event to get updated sizes when the window changes.
javascript
/* Wrong way: may not reflect actual visible window size */ const wrongWidth = document.body.clientWidth; /* Right way: use window.innerWidth */ const rightWidth = window.innerWidth;
Quick Reference
- window.innerWidth: Width of the viewport in pixels.
- window.innerHeight: Height of the viewport in pixels.
- window.addEventListener('resize', callback): Listen for window size changes.
Key Takeaways
Use window.innerWidth and window.innerHeight to get the visible window size in pixels.
Listen to the 'resize' event to update window size dynamically.
Avoid using document.body.clientWidth for window size as it can be inaccurate.
window.innerWidth and innerHeight reflect the viewport excluding browser chrome and scrollbars.