Prevent on resize event when opens phone keyboard (JS)

Viewed 665

Good day guys, I hope someone knows how I can run a function only when the phone device changes orientation. I mean exactly ONLY when the phone device changes its orientation, not when keyboard opens >> this is the problem.

I know this window.innerWidth > window.innerHeight, and in conjunction with resize event, it gives me what I need: determination landscape and portrait. But I just now tested my website on Android, and when the keyboard opens this gives me a fake landscape result, I mean device orientation not was changed for real. So, this is the question, how I can run my function when the phone (Android, iOS) changes its orientation, but prevent it if the orientation changes because of keyboard opens.

2 Answers

You can use window.screen and all what it gives to you!

The keyboard causes a change in the height of the screen. If you don't want to, or don't need to handle this, then you can filter out changes to just the width:

let windowWidth = window.innerWidth;
window.addEventListener('resize', function(event) {
    if (window.innerWidth != windowWidth) {
        windowWidth = window.innerWidth;
        handleEvent();
    }
});
Related