Zen-Lee Chai
Zen-Lee Chai

Reputation: 451

How to detect screen size for responsive web design?

I googled this and got a quirksmode site that gives you your screen size. Pulling up the console I see that screen.width and screen.height are directly available from the window object.

I want to do the detection in pure JavaScript to get started. Can I use this property across all devices and browsers - mobile, tablet, PC and Chrome, Safari, IE, Firefox.

I don't care about the view port changing due to re-sizing etc. Just the actual size of the screen which does not change.

I was hoping there was a single property I could check across devices and browsers.

Here is some general info by wikipedia on responsive web design.

Upvotes: 19

Views: 57944

Answers (5)

dreamLo
dreamLo

Reputation: 1860

if (window.visualViewport.width <= 576) {
  console.log('phone')
} else if (window.visualViewport.width <= 768) {
  console.log('tablet')
} else if (window.visualViewport.width <= 992) {
  console.log('laptop')
} else { // 1200
  console.log('desktop')
}

Upvotes: -1

Sambuxc
Sambuxc

Reputation: 479

Well, screen.width & screen.height will detect the width and height of the screen and not necessarily the users browser width/height. So this may not provide an accurate reading if the user resizes the browser. https://developer.mozilla.org/en-US/docs/Web/API/Screen/width

Another way would be to use window.innerWidth and window.innerHeight. Regardless of the device/screen, this would provide the actual browser width/height. https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth

A bit of testing would determine which one would be most suitable for your requirements.

You may also want to read about Layout Viewport https://developer.mozilla.org/en-US/docs/Glossary/Layout_viewport

Upvotes: 0

Karthik Sagar
Karthik Sagar

Reputation: 444

This is what worked for me after long hunch. These attributes below provide responsive sizes based on new tab size.

window.innerWidth
window.innerHeight

Upvotes: 4

l0w_skilled
l0w_skilled

Reputation: 830

Take a look at Get the device width in javascript

Media Queries work in js too:

if (window.matchMedia('screen and (max-width: 768px)').matches) {}

Another way would be:

var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

Upvotes: 53

user2258887
user2258887

Reputation:

screen.width is the property your are looking for.

Upvotes: 9

Related Questions