Home >Web Front-end >CSS Tutorial >How Can I Get the User's Device Width, Not Viewport Width, in JavaScript?

How Can I Get the User's Device Width, Not Viewport Width, in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 13:11:11362browse

How Can I Get the User's Device Width, Not Viewport Width, in JavaScript?

Detecting Device Width in JavaScript

Question:

How can we obtain the user's device width, distinct from the viewport width, using JavaScript?

Answer:

CSS media queries provide a method for this using the max-device-width property. However, when working with JavaScript bindings, we are often limited to accessing the viewport width.

Elegant Solution:

To elegantly address this, we can utilize the screen.width property to retrieve the device screen width. In some instances, such as when dealing with desktop browsers where window size may differ from device screen size, we can use window.innerWidth instead.

Cross-Platform Compatibility:

For a comprehensive solution that works across both mobile and desktop browsers, consider the following:

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

This ensures that we obtain the correct device width regardless of the viewing context.

The above is the detailed content of How Can I Get the User's Device Width, Not Viewport Width, in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn