-
-
Save OrganicPanda/8222636 to your computer and use it in GitHub Desktop.
// Demo: http://jsfiddle.net/pFaSx/ | |
// Create an invisible iframe | |
var iframe = document.createElement('iframe'); | |
iframe.id = "hacky-scrollbar-resize-listener"; | |
iframe.style.cssText = 'height: 0; background-color: transparent; margin: 0; padding: 0; overflow: hidden; border-width: 0; position: absolute; width: 100%;'; | |
// Register our event when the iframe loads | |
iframe.onload = function() { | |
// The trick here is that because this iframe has 100% width | |
// it should fire a window resize event when anything causes it to | |
// resize (even scrollbars on the outer document) | |
iframe.contentWindow.addEventListener('resize', function() { | |
try { | |
var evt = document.createEvent('UIEvents'); | |
evt.initUIEvent('resize', true, false, window, 0); | |
window.dispatchEvent(evt); | |
} catch(e) {} | |
}); | |
}; | |
// Stick the iframe somewhere out of the way | |
document.body.appendChild(iframe); |
Since the initUIEvent
function is now deprecated (see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent),
var evt = document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
Should be replaced with:
var evt = new UIEvent('resize');
Thanks for sharing! It works!
Awesome!! This helps me a lot!!
Thank you! This is fantastic!!!
For anyone interested, I've forked this into a React component https://gist.github.com/AdamMcCormick/d5f718d2e9569acdf7def25e8266bb2a
Now I understand why "problem solving" is important in programming ! Thanks 😄
Very nice! I've adapted this as a React hook https://gist.github.com/curran/0e30c621fe4fc612bf7feb0938a68e4d
Since the
initUIEvent
function is now deprecated (see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent),var evt = document.createEvent('UIEvents'); evt.initUIEvent('resize', true, false, window, 0);Should be replaced with:
var evt = new UIEvent('resize');
Not only is this deprecated, but also throws this error in the console:
Property 'initUIEvent' does not exist on type 'UIEvent'. Did you mean 'initEvent'?
Any other clue or workaround for this?
Sorry @cyberdante I wrote this in a hurry years ago and it never actually made it to production so I didn't keep this up to date. I wonder if @curran, @AdamMcCormick or @JasperTey could point to a fix?
You can use window.visualViewport?.addEventListener('resize', update);
for this nowadays. It was introduced in 2019 and supported by basically every modern browser. The resize event triggers for any resize, including the opening and resizing of the on-screen keyboard on iOS and the scrollbar appearing.
Thanks @MartijnHols! It's nice to know there is a clean way of achieving this 10 years since I first posted my hacky solution!
Oh man, this is brilliant. Thank you for sharing it!