Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

orientationchange event fires scroll & resize event

For a project I'm working on, I ran into a strange issue, for which I could not find an answer on here (or anywhere else).

I tried creating a Fiddle to demonstrate what happens, but due to the nature of my script, and the way jsfiddle functions, it is not working correctly. Anyway, here's a link to the Fiddle so at least you'll have the code.

What I want to happen

Execute a single handler (onViewportChange) on three possible window events: resize, orientationchange and scroll. Based on the event type, the handler will figure out what to do. Sounds pretty straightforward.

What I did

For this example, I have limited the handler to echo the event type, for testing purposes:

var onViewportChange = function(e) {
    alert(e.type);
};

I bind the handler to the events: (I have also tried .bind() with an array of events, and several separate binds)

$(window).on({
    'orientationchange resize scroll' : function(e){
        onViewportChange(e);
    }
});

The HTML is completely empty, except for the arbitrary base elements (doctype, html, body and ofcourse jquery and this script)

What actually happens

And now it gets weird: the events fire fine on desktop browsers (mainly due to the lack of an orientationchange event firing), but not on mobile devices (tested on an iOS6+ iPad 3rd generation and an iOS6+ iPhone 5). When I rotate my the device(s);

  • The iPad and iPhone fire all three: orientationchange, resize followed by scroll
  • Chrome on the iPhone fires resize followed by orientationchange
  • An Android phone I borrowed triggers orientationchange followed by resize

(Note that the order of events may not be accurate because of race conditions.)

And here's why I linked it to the orientationchange event: When I remove the orientationchange event (leaving resize and scroll), only the scroll event is fired on a device rotation, but no longer the resize event.

I don't understand why all events fire at once. At least; I can imagine that a resize is triggered on an orientationchange because the window dimensions change, but a scroll?

Does anyone know why this is happening?

edit I've set up a demo here: http://beta.hnldesign.nl/orientation/index.html

like image 777
Klaas Leussink Avatar asked Oct 06 '22 11:10

Klaas Leussink


1 Answers

Hmmmm, try this (extracted from jQuery API docs...) http://api.jquery.com/on/

$(window).on({
  orientationchange: function(e) {
    onViewportChange(e);
  }, resize: function(e) {
    onViewportChange(e);
  }, scroll: function(e) {
    onViewportChange(e);
  }
});

This should work... maybe you need to tweak the code a little bit more

like image 62
Guillermo Avatar answered Oct 12 '22 19:10

Guillermo