skip to Main Content

I realize similar questions have been asked before regarding getting device sizes etc. but there seems to be disagreement about the exact way to go about this.

Suppose I have media-queries (e.g. Twitter Bootstrap) with

Extra small devices Phones (<768px)

Small devices Tablets (≥768px)

Medium devices Desktops (≥992px)

Large devices Desktops (≥1200px)

Now, I’d like to be able to use Javascript to essentially get the same output. In other words, the css media-query pixel number rather than the actual screen dots. i.e. I don’t need to get the exact answer, but I want to avoid being out by a factor or 2 or 3 because I’m getting ‘screen dots’ rather than css pixels.

I’m more concerned with mobile devices – especially Android – than desktop. Is screen.width reliable for this? Or jQuery(document).width()?

(This is for a research project and while I’m aware that it’s basically impossible to detect tablet vs. phone, I’d like an indication of the size of the devices people are using. The user experience will not be dictated by the results.)

3

Answers


  1. My favourite way of doing this is as follows (jQuery):

    var viewportWidth = $(window).width();
    // Then  create if statements and execute code accordingly... 
    if (viewportWidth <= 767) {
               // execute code
    } else if (viewportWidth >= 768) {
               // execute this
    }
    

    You can also execute code for viewports between widths, such as:

    if (viewportWidth >= 768 && viewportWidth <= 991) {
       //execute this
    }
    

    This would execute the code when the viewport is between 768px and 991px…

    Login or Signup to reply.
  2. You can get window width using Javascript like this

    var wid = window.innerWidth;
    

    Extra small devices Phones (<768px)

    if (wid < 767) {
       //execute this
    }
    

    Small devices Tablets (≥768px)

    if (wid >= 768 && wid <= 991) {
       //execute this
    }
    

    Medium devices Desktops (≥992px)

    if (wid >= 992 && wid <= 1199) {
       //execute this
    }
    

    Large devices Desktops (≥1200px)

    if (wid >= 1200) {
       //execute this
    }
    
    Login or Signup to reply.
  3. This is the script I always use:

    function viewport() {
        var e = window, a = 'inner';
        if (!('innerWidth' in window )) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
    }
    

    You can then call it to a variable, and read its height and width properties:

    var vp = viewport();
    var vpWidth = vp.width;
    var vpHeight = vp.height;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search