Detect Orientation Change

Unless your mobile application allows for only portrait or only landscape views, there's a good chance you will need to adjust a few things. Even if you've built your layouts in a fluid fashion, you may need to programmatically make some changes. There are a few strategies for knowing when pages have changed, so let's check out how we can detect orientation changes on mobile devices.

orientationchange Event

This method is what you would expect from a mobile API; a simple orientationchange event on the window:

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
	// Announce the new orientation number
	alert(window.orientation);
}, false);

During these changes, the window.orientation property may change. A value of 0 means portrait view, -90 means a the device is landscape rotated to the right, and 90 means the device is landscape rotated to the left.

resize Event

Some devices haven't provided the orientationchange event, but do fire the window's resize event:

// Listen for resize changes
window.addEventListener("resize", function() {
	// Get screen size (inner/outerWidth, inner/outerHeight)
	
}, false);

A bit less obvious than the orientationchange event, but works very well.

Screen Sizing

There are a few properties you can retrieve from the window object to get screen size and what I consider "virtual" screen size:

These don't give you the orientation, of course, but using some simple math, you can find out if the window is currently wider or taller.

Media Queries

We can identify orientation by CSS media queries as well:

/* portrait */
@media screen and (orientation:portrait) {
	/* portrait-specific styles */
}
/* landscape */
@media screen and (orientation:landscape) {
	/* landscape-specific styles */
}

If you'd like to get clever, you can code a periodical "watcher" with JavaScript to check the background color of a block and fire your own orientation change.

matchMedia

The native window.matchMedia method allows for live media-querying. We can use the media queries above to find out if we're in portrait or landscape view:

// 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
	}
});

So there are a few ideas and options for you. I'd love to hear any more practical techniques you've used!