JavaScript resize event on scroll - mobile
Asked Answered
R

2

30

I'm trying to make a website for mobile. I'm having the "resize" event bounded on window, which should rearrange elements when the mobile device is turning (portrait <-> landscape). On iPhone and Samsung Galaxy SII, the event is triggered when I'm scrolling down the page, and that's not good.

How can I fix this?

Recapture answered 20/2, 2012 at 13:31 Comment(1)
F
9

Use the onOrientationChange event and the window.orientation property instead.

Also see this answer.

Here link to a test page.

Fecteau answered 20/2, 2012 at 13:35 Comment(0)
Q
54

Cache the width of the viewport and on resize return false if the width is still the same.

A small jQuery snippet:

    var cachedWidth = $(window).width();
    $(window).resize(function(){
        var newWidth = $(window).width();
        if(newWidth !== cachedWidth){
            //DO RESIZE HERE
            cachedWidth = newWidth;
        }
    });
Quotable answered 19/6, 2014 at 16:48 Comment(6)
This was the answer I was looking for. So nice. OP This should be the accepted answer. This is the correct way to go about it.Mcfadden
@LukeFlego it is the best way to fix this bug, not ideal code though. Sometimes the easiest fix is the best :)Quotable
Ran into the same issue, and this fixed it. This is the correct answer.Barracoon
This looks like jQuery and there's nothing about it in the question.. but thank you, sidonaldson, for the answer – not bad at all.Kirstiekirstin
@Kirstiekirstin correct. I'll update the answer to make that clearQuotable
window.innerWidth for all wanting the jQuery free answer.Fundy
F
9

Use the onOrientationChange event and the window.orientation property instead.

Also see this answer.

Here link to a test page.

Fecteau answered 20/2, 2012 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.