How to get css-pixel width (media request) using Javascript?

I understand that similar questions were asked before getting the dimensions of the device, etc., but there seems to be disagreement about the exact way to do this.

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

Optional Small Devices Phones (<768px)

Small Pill Devices (≥768px)

Medium Devices Desktop Computers (≥992px)

Large Devices Desktop Computers (≥1200px)

Now, I would like to be able to use Javascript to get the same result. In other words, the pixel number of the css media request is not the actual points on the screen. those. I don’t need to get an exact answer, but I want to avoid getting out of one or two or three, because I get “screen points” and not css pixels.

I'm more interested in mobile devices - especially Android - than the desktop. Is screen.width reliable for this? Or jQuery(document).width() ?

(This is for a research project, and although I know that in principle it is impossible to detect a tablet compared to a phone, I would like to indicate the size of devices used by users. The user interface will not be dictated by the results.)

+5
source share
3 answers

My favorite way to do it 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, for example:

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

This will execute the code when the viewport is between 768px and 991px ...

+2
source

You can get the width of the window using Javascript like this

 var wid = window.innerWidth; 

Optional Small Devices Phones (<768px)

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

Small Pill Devices (≥768px)

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

Medium Devices Desktop Computers (≥992px)

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

Large Devices Desktop Computers (≥1200px)

 if (wid >= 1200) { //execute this } 
+1
source

This is a 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' ] }; } 

Then you can call it in a variable and read its height and width properties:

 var vp = viewport(); var vpWidth = vp.width; var vpHeight = vp.height; 
0
source

Source: https://habr.com/ru/post/1236795/


All Articles