Search code examples
javascripthtmlcssresponsive-design

Why is my responsive design working when I use the mobile device tool, but if I decrease the browser itself, it's not working?


When I use the toggle device tool on the Inspect tools of my browser, my responsive design works as expected, but if I instead just minimize the browser, then it's not working. Is this a bug?

I am using JavaScript to detect the screen size. This is the function:

if(window.screen.availWidth > 1024 && window.screen.availWidth < 1200) { 
 ...
} else if(window.screen.availWidth > 1200) { 

... 

}

I have noticed that the first condition window.screen.availWidth > 1024 && window.screen.availWidth < 1200 is not met when I shrink/enlarge the browser itself, but it's met, as it should be, when I use the mobile tool from the inspect tools.

This is the mobile tool I am referring to:

enter image description here

Is this a bug, or is it related to the availWidth property?


Solution

  • window.screen.availWidth returns the width of the device screen, not the browser screen. When you use the mobile tool, the browser emulates a mobile device and hence the webpage thinks that the screen is of a mobile, regardless of the browser size. However, when window.screen.availWidth takes the width of the screen (your monitor) and it does not take the size of the browser window.

    You might want to take a look at the window.innerWidth property instead.