7537247
7537247

Reputation: 323

Redirect to mobile page when width is too small

Since my website doesn't look good at all on a small screen, I want to create a JS function that redirects me to a mobile version of the page when width of the screen is smaller than or equal to 800px.

Here is the code for it:

if (screen.width <= 800) {
  document.location ="index_mobile.html";
};

If the code works, then when I shrink down the browser window to 800px wide, the index_mobile.html should show up. But it is not showing up right now. Does anyone know what's going on?

http://jsfiddle.net/RZMmV/

Upvotes: 3

Views: 2269

Answers (2)

hexist
hexist

Reputation: 5250

screen.width will return the width of the monitor, not the window, so you can't just shrink your browser window down to get a different value. To do that, you'll want to use window.outerWidth or something.

Upvotes: 0

6502
6502

Reputation: 114579

Mobile browsers do not report or use the real device resolution because this would make basically all websites on the internet unusable.

What they do is creating a "virtual screen" that has a resolution that is closer to the resolution of a desktop PC and then will implement zooming on the page.

If you want to know the real device resolution you need to disable automatic scaling done on the device. For example for iOS and Android devices this can be done adding

<meta name="viewport"
      content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

to the <head> section of your page. This informs the browser that the page has been designed for handling low-resolution devices and disables the virtual screen layer.

Upvotes: 2

Related Questions