Sometimes, we want to detect rotation of Android phone in the browser with JavaScript.
In this article, we’ll look at how to detect rotation of Android phone in the browser with JavaScript.
How to detect rotation of Android phone in the browser with JavaScript?
To detect rotation of Android phone in the browser with JavaScript, we can listen for the orientationchange
event.
For instance, we write
const supportsOrientationChange = "onorientationchange" in window;
constorientationEvent = supportsOrientationChange
? "orientationchange"
: "resize";
window.addEventListener(
orientationEvent,
() => {
console.log(window.orientation, screen.width);
},
false
);
to get the event name by checking "onorientationchange" in window
.
If onorientationchange
is available that means we can listen for the orientationchange
event.
Otherwise, we listen for the resize
event.
Then we call addEventListener
to listen to either event and get the orientation
and screen’s width with screen.width
.
Conclusion
To detect rotation of Android phone in the browser with JavaScript, we can listen for the orientationchange
event.