Home > Article > Web Front-end > How Can I Detect Orientation Changes in Mobile Browsers using JavaScript?
Detecting Orientation Changes in Browsers on Mobile Devices using JavaScript
Modern mobile browsers provide ways to detect changes in the orientation of the device, allowing developers to adjust the user interface or provide different experiences based on the current orientation.
Detecting Orientation with Screen Orientation API
To use this API, you can do the following:
Here's an example snippet:
window.addEventListener("DOMContentLoaded", () => { const output = document.getElementById("o9n"); const displayOrientation = () => { const screenOrientation = screen.orientation.type; output.innerHTML = `The orientation of the screen is: ${screenOrientation}`; // Check the orientation and log messages accordingly }; if (screen && screen.orientation !== null) { try { window.screen.orientation.onchange = displayOrientation; displayOrientation(); } catch (e) { output.innerHTML = e.message; } } });
The above is the detailed content of How Can I Detect Orientation Changes in Mobile Browsers using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!