While waiting for responsive design to find the way into a legacy web site, I would like to redirect a browser to a mobile version if the screen is smaller than 480px
Hunting around I came up with
var isSmall = window.matchMedia ?
window.matchMedia("screen and (max-width: 480px)") :
screen.width<=480;
Question
Is this acceptable in 2014 or is there a better/safer/newer method to do what I want without using useragent sniffing?
References
MDN Window.matchMedia
JavaScriptKit CSS media query matching in JavaScript using window.matchMedia()
QuirksMode screen.width is useless (hence the addition of matchMedia)
While waiting for responsive design to find the way into a legacy web site, I would like to redirect a browser to a mobile version if the screen is smaller than 480px
Hunting around I came up with
var isSmall = window.matchMedia ?
window.matchMedia("screen and (max-width: 480px)") :
screen.width<=480;
Question
Is this acceptable in 2014 or is there a better/safer/newer method to do what I want without using useragent sniffing?
References
MDN Window.matchMedia
JavaScriptKit CSS media query matching in JavaScript using window.matchMedia()
QuirksMode screen.width is useless (hence the addition of matchMedia)
-
1
Make sure to check up on iPhone 4+ as they have a screen width of
640px
but report their screen width as320px
for legacy reasons. – gaynorvader Commented Apr 17, 2014 at 13:48 - But since they support matchMedia as far as I understand does that not return false before using screen.width? – mplungjan Commented Apr 17, 2014 at 13:51
- Fwiw, the slight advantage you have with user agent sniffing is that you can do this server side, resulting in a slightly faster experience because a redirect doesn't contain a document. You would probably still want a cookie based switch between mobile / desktop, though. – Ja͢ck Commented May 9, 2014 at 6:03
- Seems still valid in 2023. Here is an article from 2020 webdevetc./blog/matchmedia-events-for-window-resizes – mplungjan Commented Mar 22, 2023 at 6:35
3 Answers
Reset to default 0You could use a polyfill such as https://github./paulirish/matchMedia.js/
you can use bootstrap http://getbootstrap./ or
foundation http://foundation.zurb./
these two frameworks has a powerful multi device layouts.
Yes there is lot of tricky ways :) to choose windows width but our Team's view you didn't have to include any tricks to know just windows.width because jQuery has a .width() function like:
var window_width = $(window).width();
if( window_width <= 480 ){
console.log(window_width);
}
Iphone 4S, Iphone 5, Iphone 5S Every one's Screen Width is 320px. Your Mobile Resolution isn't your mobile's Screen Width. so when you include your tricks to know just windows width or something you just increase your Application's loadspeed this gonna be a problem for your user. But you know that was the designer's issue why they plicate the designs for developers & for End Users. :)