Created
March 23, 2021 03:56
-
-
Save anhskohbo/22ae91039a7db539210ad69e79c039a5 to your computer and use it in GitHub Desktop.
handleOrientation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Document</title> | |
</head> | |
<body> | |
<script> | |
(function () { | |
function debounce(func, wait, immediate) { | |
var timeout; | |
return function () { | |
var context = this, | |
args = arguments; | |
clearTimeout(timeout); | |
timeout = setTimeout(function () { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}, wait); | |
if (immediate && !timeout) func.apply(context, args); | |
}; | |
} | |
var isPortrait = function () { | |
if (window.screen.orientation && "onorientationchange" in window) { | |
return String(window.screen.orientation.type).includes("portrait"); | |
} | |
if ("orientation" in window) { | |
return Math.abs(window.orientation) !== 90; | |
} | |
return window.innerHeight / window.innerWidth > 1; | |
}; | |
var isLandscape = function () { | |
if (window.screen.orientation && "onorientationchange" in window) { | |
return String(window.screen.orientation.type).includes("landscape"); | |
} | |
if ("orientation" in window) { | |
return Math.abs(window.orientation) === 90; | |
} | |
return window.innerHeight / window.innerWidth < 1; | |
}; | |
function handleOrientation() { | |
if (isPortrait()) { | |
alert("Please use Landscape"); | |
} | |
} | |
// Detect whether device supports orientationchange event, | |
// otherwise fall back to the resize event. | |
var orientationEvent = "resize"; | |
if ("onorientationchange" in window) { | |
orientationEvent = "orientationchange"; | |
} | |
// Listen for changes in orientation. | |
if (window.addEventListener) { | |
window.addEventListener( | |
orientationEvent, | |
debounce(handleOrientation, 150), | |
false | |
); | |
} else if (window.attachEvent) { | |
window.attachEvent( | |
orientationEvent, | |
debounce(handleOrientation, 150) | |
); | |
} | |
handleOrientation(); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment