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);
orientationchange
, resize
followed by scroll
resize
followed by orientationchange
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With