Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the 'css-pixel' (media-query) width using Javascript?

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.)

like image 515
Gazzer Avatar asked Oct 18 '22 21:10

Gazzer


2 Answers

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...

like image 118
David Wilkinson Avatar answered Oct 31 '22 19:10

David Wilkinson


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
}
like image 29
Amin Kodaganur Avatar answered Oct 31 '22 17:10

Amin Kodaganur