Most mobile-device screens aren't square - they're rectangular. As such, and unlike desktop or laptop devices, there's a marked difference when we tilt our phones or tablets. We can provide our users with a richer experience when we present a different view or different interactions with content presented in landscape versus portrait mode. Showing/hiding content, changing a side-by-side layout into a stacked vertical layout, and other orientation-state reactions are enhancements to your pages that your mobile users will appreciate.
The jQuery Mobile orientationchange event handler allows us to capture changes in the orientation of the device:
|orientationchange||Triggers when a device orientation changes (by turning it vertically or horizontally). When bound to this event, your callback function can leverage a second argument, which contains an orientation property equal to either "portrait" or "landscape". These values are also added as classes to the HTML element, allowing you to leverage them in your CSS selectors. Note that we currently bind to the resize event when orientationchange is not natively supported, or when $.mobile.orientationChangeEnabled is set to false.|
In this next example, we selectively show content based on the orientation of the device. Two paragraphs live in the main content div; the paragraph with class landscape shows when the phone has landscape orientation, and the paragraph with class portrait shows when the phone has portrait orientation:
Open Events/Demos/orientation.html to test it out and to view the code.
We create a function,
setContent, which when executed will check to see if the parameter passed to it (
orien) is undefined; if not, then we must be dealing with a device for which orientation makes sense - a phone rather than a desktop.
setContent can be invoked in two different ways. When the page initially loads (
$(document).on('pagecreate', '#home', function()), we pass the value of
setContent - this has a value of 90 or -90 (for landscape orientations) or 0 or 180 (for portrait orientations).
We also check for orientation-state changes once the page is live (
$(window).on('orientationchange', function(event)), passing the value of
setContent. This parameter has a value of "landscape" or "portrait".
If its parameter has one of the numeric values, function
setContent translates the value into "landscape" or "portrait". It then uses jQuery's
show() functions to hide or show the correct paragraphs.