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
My favourite way of doing this is as follows (jQuery):
You can also execute code for viewports between widths, such as:
This would execute the code when the viewport is between 768px and 991px…
You can get window width using Javascript like this
Extra small devices Phones (<768px)
Small devices Tablets (≥768px)
Medium devices Desktops (≥992px)
Large devices Desktops (≥1200px)
This is the script I always use:
You can then call it to a variable, and read its height and width properties: