A Guide to Dynamically Obtaining Browser Screen Width and Height with jQuery [Updated 2023]

Although it's 2023, many developers still rely on the jQuery library for its ease of use in JavaScript. If you need to obtain the screen width and height of your browser window using jQuery, look no further than the following code. As you resize your browser window, the width and height values of the frame are automatically displayed.

There could be various reasons one may want to get the width and height of a web browser,

  1. In order to create a responsive website that adapts to the different screen sizes (mobile/laptops), you need to know the screen width and height so that you can adjust the layout accordingly.
  2. Knowing the screen size of the user could help you can customize the user experience for different devices. For example, you might want to display a mobile-friendly version of your site on small screens or show a larger version of images on larger screens.
  3. This may also help to track the screen size of your visitors to help you analyze their behavior and preferences. For example, you might find that visitors using smaller screens tend to click on certain areas of your site more frequently than those using larger screens.
  4. If you display ads on your website, it could be so that you need to know specific screen sizes for displaying ads, so by knowing the screen size, you can ensure that the appropriate ad is displayed to the user.

This code can be quite handy when testing the responsive design of your website. You can view this page on various devices to get the height and width.

Code Example:
<!DOCTYPE html>
<script type="text/javascript" src="../js/jquery-1.10.2.min.js" >
#display {
        width: auto;
        background-color: #ccc;
        color: #222;
        margin-left: 5px;
        text-align: center;
$("#display").html("<b>Width</b> : " + 
       $(window).width() + ",<b>Height : </b>" +
$(window).resize(function() {
        $("#display\").html("<b>Width</b> : " +
        $(window).width() + ",<b>Height : </b>" +
<div id="display"></div>

You can see the below gif file - you can see that as we resize the browser window, we get the correct width and height size in pixels.

Get Browser width and height using jQuery
Get Browser width and height using jQuery

⛏️ Note: There is an easier way to do this using the Chrome browser Inspect option, Right Click on any web page and click on Inspect, click on "Toggle Device Toolbar" and select the responsive option, drag the width and height to know how your page renders and what the page dimensions are.


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap