Search code examples
jqueryviewportmeta

meta viewport affecting jQuery?


so i'm currently trying to optimize my blog for mobile. I chose the way to add an additional CSS file for devices with a window-width smaller than 768 pixels. My page is 1022 Pixels wide in desktop mode, the mobile version has a fluid width.

So my code in the head-section is this:

var mobileSite = false;
if($(window).width() < 768) {
    mobileSite = true;
    $('head').append('<link rel="stylesheet" href="mysite.com/mobile.css" type="text/css" />');
}

Works like a charm so far. Next thing is to stop the iPad (not tested on Andriod yet) from zooming into the content section. In either mode, the iPad should display the full page without zooming in. So i added this:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

without success. As far as i understand, width=device-width is to tell the browser what size the page has, so the browser knows how far it should zoom out. I tried initial-scale=0.7which helped but i guess thats only for the specific device i tried it on, which was the iPad 2. So i tried width=1022 which helped - the iPad shows the full page by default without zooming in. But the side effect was that other mobile devices like the iPhone or a Lumia 920 didn't load the mobile CSS anymore which is very strange to me. But i thought i could go around with a specific meta for mobile and desktop version of my site:

var mobileSite = false;
if($(window).width() < 768) {
    mobileSite = true;
    $('head').append('<link rel="stylesheet" href="mysite.com/mobile.css" type="text/css" />');
    $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />');
} else {
    $('head').append('<meta name="viewport" content="width=1022, initial-scale=1.0, maximum-scale=1.0" />');
}

Same effect here. The mobile version does not load anymore. So the mobile.css is not added.

Where is the problem?

What i want: Show the desktop version of my site on any device with a window-width larger than 768 pixels fully zoomed out and load the mobile.css for every device window-width<768 pixels.


Solution

  • You can use your viewport

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    

    alongside CSS media queries to target certain viewport sizes. The attached JSFiddle does what you're trying to achieve without the need to use Javascript: http://jsfiddle.net/3muzkfdt/

    Resize the result pane to see the page using different CSS.

    If you want the CSS modularised into a mobile.css and desktop.css, simply import the CSS as follows:

    @media (max-width: 768px){
       @import 'mobile.css';
    }
    
    @media (min-width: 769px){
       @import 'desktop.css';
    }
    

    See MDN for further info on Media Queries and their use: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries