Home > Web Front-end > JS Tutorial > body text

How Do I Detect the Screen Resolution of a User\'s Device Using JavaScript?

DDD
Release: 2024-10-26 02:55:02
Original
739 people have browsed it

How Do I Detect the Screen Resolution of a User's Device Using JavaScript?

Detecting Screen Resolution in JavaScript

In web development, it is often necessary to determine the resolution of the user's device. JavaScript provides a convenient way to retrieve this information for most modern browsers.

Browser Compatibility

The window.screen object is supported in all major browsers, including:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Opera

Accessing Screen Resolution

To obtain the screen resolution, use the following properties of the window.screen object:

  • availHeight: The available height of the screen in pixels, excluding toolbars, menus, etc.
  • availWidth: The available width of the screen in pixels, excluding toolbars, menus, etc.
  • height: The absolute height of the screen in pixels, including toolbars, menus, etc.
  • width: The absolute width of the screen in pixels, including toolbars, menus, etc.

Native Resolution for Mobile Devices

To determine the native resolution of a mobile device, multiply the available width and height by the device pixel ratio:

<code class="javascript">nativeWidth = window.screen.availWidth * window.devicePixelRatio;
nativeHeight = window.screen.availHeight * window.devicePixelRatio;</code>
Copy after login

Getting Absolute Resolution

If you need the absolute resolution of the screen (including toolbars and menus), use the height and width properties instead of availHeight and availWidth.

Example

The following code retrieves the available screen resolution:

<code class="javascript">let availHeight = window.screen.availHeight;
let availWidth = window.screen.availWidth;
console.log("Available screen resolution: " + availWidth + "x" + availHeight);</code>
Copy after login

The above is the detailed content of How Do I Detect the Screen Resolution of a User\'s Device Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template