Reputation: 2406
I want execute a function when the size of the current windows has changed.
I have this very simple code : (foo.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
<script>
function resize() {alert("FOO");}
window.onresize = resize;
</script>
</html>
On Firefox Quantum v60.4 (Desktop), this code works like a charm. When I resize the firefox window, the alert is showed. And when I only load the page "foo.html" the alert "FOO" does not appears.
But :
On Chrome v71.0.3578 (Desktop), when I resize the window the alert appears twice.
Worst, On my Android smartphone (with Firefox v67.0.2), the alert appears when I load the page (I don't resize the page, just load)
Is here a way for handle the resize window event ONLY ONE TIME when I resize the windows or pass from the portrait to the landscape mode on Smartphone ?
Thanks for help !
EDIT :
With this code, I can prevent the Chrome twice fire :
var resizeTimer;
window.onresize = function(){
if (resizeTimer){
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function(){
alert("FOO");
}, 50);
};
But on Firefox (Android), I keep the same issue. The alert "FOO" is showed when I load the page. (On Smartphone, I want to execute my code only when the user pass from the portrait mode to the landscape mode)
Upvotes: 0
Views: 193
Reputation: 22320
And why not have something like this?
var CurrentWindowSize = { w: document.body.clientWidth, h: document.body.clientHeight }; // only Chrome has correct values here
window.onresize = function(e)
{
let width = e.target.outerWidth
, height = e.target.outerHeight
;
if (width != CurrentWindowSize.w
|| height != CurrentWindowSize.h)
{
CurrentWindowSize.w = width;
CurrentWindowSize.h = height;
WindowIsResized();
}
}
function WindowIsResized() {
// your stuff...
}
Upvotes: 1