Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynxerzhang/741c17ba53796d845a478f5ca576350b to your computer and use it in GitHub Desktop.
Save lynxerzhang/741c17ba53796d845a478f5ca576350b to your computer and use it in GitHub Desktop.
JavaScript: Detect Orientation Change on Mobile Devices
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
}, false);
// Listen for resize changes
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
}, false);
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
// If there are matches, we're in portrait
if(mql.matches) {
// Portrait orientation
} else {
// Landscape orientation
}
// Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
// Changed to portrait
}
else {
// Changed to landscape
}
});
/* portrait */
@media screen and (orientation:portrait) {
/* portrait-specific styles */
}
/* landscape */
@media screen and (orientation:landscape) {
/* landscape-specific styles */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment