How to get screen width from Chrome Dev Tool in JavaScript

I want to execute a specific javascript function depending upon the screen size. For example, if the page is viewed on iPhone 8 or 10, I want to execute the function1, otherwise, I want to execute function2. I am using Chrome Dev tools to simulate it. The following is my sample code.

$(document).ready(function() {
  //getting screen width by plain javascript
  w = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
  alert("JS Width: " + w); //on chrome dev tools w corresponds to 980 for iPhone 8  

  var targetWidth = 375;

  //getting screen width by plain jQuery
  alert("Width: " + $(window).width()); //on chrome dev tools this value corresponds to 980 for iPhone 8

  if ($(window).width() >= targetWidth) {
    //Add javascript for screens wider than or equal to 375here
    alert("big");
  } else {
    //Add javascript for screens smaller than 375 here
    alert("small");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

So, whatever cell phone size I use on the Chrome dev tool, the size always comes out as 980. Since I don’t have a server where I could run my website and use an actual cell phone to test my code, I am wondering how to get the width of a resized screen size from Chrome dev tools.

16 thoughts on “How to get screen width from Chrome Dev Tool in JavaScript”

Leave a Comment