1

so I try to get the width of the device using jquery I made responsive website with 2 interface for laptop and mobiles but the problem is it doesn't work in mobile even the dimension of the div test was out of size in mobiles please help me the code that I use for redirecting is below with comments

<html>
<head>
    <script src="./js/jquery-3.2.1.js"></script>
</head>
<body>
    <div id='test' style=" width: 2.54cm; height:2.54cm;"></div>
    //this div dimension works on laptop it measure exactly 2.54cm or 1nch
    //using ruler but in  mobiles it shrink and out of measure
    <script>
        //as you see I get the width of the div to get the pixel per inch
        var sqw=$('#test').width();
        var sqh=$('#test').height();
        //and I get the total width of the document
        var dheight=$(document).height();
        var dwidth=$(document).width();


    var w=dwidth/sqw;
    //and I divide the total width of the document to pixel per inch
    //the problem is the mobile show 10.98 inch where the mobile I use is 
    //miniFlare S5 cherrymobile with width of just 2.5 inches
    if(w<=7) {
        window.location.replace("./m_index.php");
    } else {
        window.location.replace("./d_index.php");
    }
</script>
</body>
</html>
sorak
  • 2,607
  • 2
  • 16
  • 24
  • 1
    Possible duplicate of [Get the device width in javascript](https://stackoverflow.com/questions/6850164/get-the-device-width-in-javascript) and [how-to-programmatically-find-the-device-width](https://stackoverflow.com/questions/9477028/how-to-programmatically-find-the-device-width-in-phonegap-jquery-mobile) – caramba Mar 06 '18 at 07:30

4 Answers4

3

Your are using jQuery. From the docs .width() they say:

This method is also able to find the width of the window and document.

// Returns width of browser viewport
$( window ).width(); // <- this is the one you are looking for!

// Returns width of HTML document
$( document ).width();
caramba
  • 21,963
  • 19
  • 86
  • 127
0
var dwidth = window.innerWidth;
var dheight = window.innerHeight;

would do the job

manish kumar
  • 4,412
  • 4
  • 34
  • 51
0

You can get cross platform using the following script:

const w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
const h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
GibboK
  • 71,848
  • 143
  • 435
  • 658
0

please try below code, it may satisfy your requirement <script> getScreensize(){ var sqw=$("body,html").width(); if(sqw<768){ //mobile screen logic } else{ //desktop screen logic } } $(window).resize(function(){ getScreensize(); }) </script>

Venkat Ch
  • 696
  • 1
  • 5
  • 16