Skip to content

Instantly share code, notes, and snippets.

@graphis
Created August 28, 2020 12:32
Show Gist options
  • Save graphis/7f7a68394598d557783456ffc32b2565 to your computer and use it in GitHub Desktop.
Save graphis/7f7a68394598d557783456ffc32b2565 to your computer and use it in GitHub Desktop.
JavaScript: window resize debouncing #snippet
/* --------------------------------------------
* Detect device orientation
* and trigger changes based on it
--------------------------------------------*/
function updateOrientation() {
// Detect whether device supports orientationchange event, otherwise fall back to the resize event
// Genius solution from http://stackoverflow.com/a/2307936
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize",
newAngle, newOrientation;
if(supportsOrientationChange){
newAngle = window.orientation;
switch(newAngle){
case 0:
case 180: newOrientation = 'portrait'; break;
case 90:
case -90: newOrientation = 'landscape'; break;
}
} else {
if(document.width < document.height){
newOrientation = 'portrait'
} else {
newOrientation = 'landscape'
}
}
// Do the processing here
/*
* Beautiful debouncing for resize event firing too much on the PC
* by Pim Jager http://stackoverflow.com/a/668185/930987
*/
resizeEvent = false;
window.addEventListener(orientationEvent, function() {
if(!resizeEvent) {
clearTimeout(resizeEvent);
resizeEvent = setTimeout(updateOrientation, 500) // half a second should be enough for a modern PC
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment