Hi ,
I have a usecase like the orientation of a particular screen should be locked (not all screens) .If we rotate the mobile , it should not change the screen orientation. Instead , when the device is rotated ,it has to show a popup message where the user has to choose whether he wants to rotate the screen or not. If he clicks on 'Yes ' , the screen is rotated. If he clicks on 'No' the screen should not be rotated and should be locked.
I am able to detect the orientation of the screen using the following javascript .But it gets triggered only when the orientation is changed.
window.addEventListener("orientationchange",func, false);
Is there a method to detect the orientation before the screen actually changes its orientation where I can implement the popup message that allows the user to select whether he want to rotate the screen or not ?
Or are there any methods that get executed just before the "orientationchange" event that could be used in this scenario?
Thanks,
Akhila K Soman
Hi @Akhila K Soman,As per my knowledge, there isn't a direct way to detect the orientation change before it happens, as the `orientationchange` event is triggered only after the orientation has changed.
However, you can use the `deviceorientation` event to detect the device's orientation before the screen rotates. This event is triggered continuously as the device's orientation changes.
Here's an example:
window.addEventListener("deviceorientation", function(event) {
// Check the current orientation
if (event.alpha > 0 && event.alpha < 180) {
// Device is in portrait mode
} else {
// Device is in landscape mode
}
// Show the popup message to ask the user if they want to rotate the screen
// If they click 'Yes', allow the screen to rotate
// If they click 'No', lock the screen orientation
});
Keep in mind that `deviceorientation` event is not supported in all browsers, so you may need to use a fallback or polyfill.
Another approach is to use the `orientationchange` event and then immediately lock the screen orientation using the `screen.orientation` API. This way, the screen will not rotate, and you can then show the popup message to ask the user if they want to rotate the screen.
window.addEventListener("orientationchange", function() {
// Lock the screen orientation
screen.orientation.lock("portrait");
// If they click 'Yes', unlock the screen orientation
// If they click 'No', keep the screen locked
Note that `screen.orientation` API is not supported in all browsers, so you may need to use a fallback or polyfill.
I hope this helps!
1. https://developer.mozilla.org/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation2. https://developer.mozilla.org/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained
3. https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent/alpha
4. https://developer.mozilla.org/en-US/docs/Web/API/Window/deviceorientation_eventThanks,Afaque Shaikh