How to Detect Screen Width in JavaScript Easily
You can detect the screen width in JavaScript using
window.innerWidth, which returns the width of the browser's viewport in pixels. Another option is screen.width, which gives the total width of the user's screen.Syntax
There are two main properties to get screen width:
window.innerWidth: Width of the browser viewport (visible area).screen.width: Total width of the physical screen.
Use window.innerWidth to detect the size of the visible browser window, which changes when resizing the window.
javascript
const viewportWidth = window.innerWidth; const screenWidth = screen.width;
Example
This example shows how to get and display the current viewport width and screen width in the browser console.
javascript
console.log('Viewport width:', window.innerWidth); console.log('Screen width:', screen.width);
Output
Viewport width: 1024
Screen width: 1920
Common Pitfalls
Many beginners confuse window.innerWidth and screen.width. Remember:
window.innerWidthchanges when you resize the browser window.screen.widthis fixed and shows the total screen size, not the browser size.- Using
document.documentElement.clientWidthcan be an alternative for viewport width but may behave differently in some browsers.
javascript
/* Wrong: Using screen.width to get viewport width */ const widthWrong = screen.width; /* Right: Use window.innerWidth for viewport width */ const widthRight = window.innerWidth;
Quick Reference
| Property | Description | When to Use |
|---|---|---|
| window.innerWidth | Width of the browser viewport in pixels | Detect visible browser window size, responsive design |
| screen.width | Total width of the user's physical screen in pixels | Detect device screen size, not affected by browser window |
| document.documentElement.clientWidth | Width of the HTML document's viewport | Alternative to window.innerWidth, sometimes more consistent |
Key Takeaways
Use window.innerWidth to get the current browser viewport width.
screen.width returns the total physical screen width, not the browser size.
window.innerWidth changes when the browser window is resized.
Avoid confusing screen.width with viewport width for responsive layouts.
document.documentElement.clientWidth can be an alternative for viewport width.