I need to use the window.resize event, but I noticed that on mobile devices, it is fired even when the keyboard is shown (for example when focusing a search field). In my case, this is not a good thing. Is the a js or css way to avoid it? Disable it or detect the 'fakeness' of the event?
Here's a basic example of detecting width/height changes. To test this on SO.com with a reliable resize event being triggered, either click the Expand snippet link and then Run, or click Run and then the Full page link. To simulate a keyboard opening, you can open dev tools and pin it to the bottom of your browser window, and then open/close it to see that only the height changes.
See Detect rotation of Android phone in the browser with JavaScript for an example of detecting device orientation changes, as it's more complicated than listening for a resize event and reading the current height/width again. For example, in Firefox dev tools, the resize even wasn't even fired when using the rotate button with the emulated device.
let width = window.innerWidth;
let height = window.innerHeight;
let statusElement = document.querySelector('p.status');
let heightElement = document.querySelector('p.height');
let widthElement = document.querySelector('p.width');
widthElement.innerText = width;
heightElement.innerText = height;
addEventListener("resize", (event) => {
let newWidth = window.innerWidth;
let newHeight = window.innerHeight;
widthElement.innerText = newWidth;
heightElement.innerText = newHeight;
if (newWidth !== width && newHeight !== height) {
// decide if you want to handle this here and/or in a separate orientationchange event listener
statusElement.innerText = 'both changed, decide what you want to do';
} else if (newWidth !== width) {
statusElement.innerText = 'only width changed, react to this';
} else if (newHeight !== height) {
statusElement.innerText = 'only height changed, probably ignore this';
} else {
// ignore the resize event if the height/width didn't actually change
}
width = newWidth;
height = newHeight;
});
<p class="status">Window loaded</p>
<p class="height"></p>
<p class="width"></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With