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 byscroll
- Chrome on the iPhone fires
resize
followed byorientationchange
- An Android phone I borrowed triggers
orientationchange
followed byresize
(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