How to Detect Window Size with jQuery

Detecting a user’s window size is one of the most common tasks in modern web development. Whether you’re designing responsive layouts, triggering animations based on viewport dimensions, or debugging screen-related issues, jQuery makes it extremely easy to get the current window width and height.

In this guide, we’ll cover everything you need to know — from basic detection to automatic resize tracking and viewport measurement.

What Is Window Size?

The window size refers to the visible area of the browser window, measured in pixels. It excludes browser UI (address bar, tabs, etc.) and represents only the active viewport where the website is rendered.

For example:

This value changes when users resize the browser or rotate their devices.

Why Detect Window Size?

Developers detect window size for many reasons:

Knowing the window size allows you to deliver a better UI regardless of the device.

Detect Window Size with jQuery

Detecting width and height with jQuery is extremely straightforward.

1. Get Window Width and Height

var width = $(window).width();
var height = $(window).height();

console.log("Window Size: " + width + " × " + height);

This retrieves the current visible viewport dimensions.

2. Detect Window Resize Automatically

Want to react when the user resizes the browser?

$(window).on('resize', function () {
    var w = $(this).width();
    var h = $(this).height();
    console.log("Resized → " + w + " × " + h);
});

This is useful for:

3. Display Window Size on Your Webpage

If you want to show the size to users:

<div id="win"></div>
function updateSize() {
    $('#win').text($(window).width() + " × " + $(window).height());
}

$(document).ready(updateSize);
$(window).on('resize', updateSize);

Viewport Size vs. Window Size

Although often used interchangeably, they are slightly different:

To get viewport size with jQuery:

var vw = $(window).innerWidth();
var vh = $(window).innerHeight();

To get layout width/height including scrollbars:

var vw2 = document.documentElement.clientWidth;
var vh2 = document.documentElement.clientHeight;

Common Use Cases for jQuery Window Size Detection

Responsive Breakpoints Example

A typical jQuery breakpoint check:

if ($(window).width() < 768) {
    console.log("Mobile view activated");
} else {
    console.log("Desktop view");
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *