Skip to content
ANALYTICS

Tracking the browser orientation status and changes

David Vallejo
Share

Last day we were talking about how to measure if our site was showing a responsive layout to our users, and today we’re going to expand that tracking post with orientation tracking for our sites.

We could use the Media Queries to match the orientation, but as this is not much standard we’re going to use the window.orientation value and the viewPort Width and Height values to guess the current page orientation and pass that info to Google Analytics and track it using a custom dimension.

orientation-tracking

Actually those API’s and features are not support for much of the current browsers, so we’re going to write some extra code to rely on the viewPort width/height values if orientation values and event are not available within the current user’s browser.

http://caniuse.com/#search=orientation
http://caniuse.com/#search=orientation

as

<script>// <![CDATA[
function getPageOrientation() { var orientation = window.orientation || window.screen.orientation; if(orientation) { // If the orientation is 0 or 180 page is in portrait mode, else landscape return (orientation == 0 || orientation == 180) ? "portrait" : "landscape"; }else{ // Let's rely on the viewPort values instead if orientation is no supporte by the browser var vpWidth= (Math.max(document.documentElement.clientWidth, window.innerWidth || 0)); var vpHeigth = (Math.max(document.documentElement.clientHeight, window.innerHeight || 0)); return vpHeigth>vpWidth ? "portrait" : "landscape";
  }
}
ga('set','dimensionYY',getPageOrientation());
// ]]></script>

As was mentioned before window.screen.orientation is a Experimental feature, therefore we’re going trying to use the orientationchange event if it’s available and if not we’ll be using to use the “resize” event that is widely supported by most browsers:

<script>
// Listen for orientation changes 
// If present use orientation value and native event 
var orientation = window.orientation || window.screen.orientation;  
if(orientation)   
     window.addEventListener("orientationchange", function() {
         ga('send', 'Orientation Change', getPageOrientation(), null, null, true);
     }, false); 
// If not, let's use resize event
} else {
     window.addEventListener("resize", function() {
         ga('send', 'Orientation Change', getPageOrientation(), null, null, true);
     }, false);
 }
</script>

And this is how you could get some insights of what are most common orientations being used by your site visitors.

Thanks fly to @SimoAhava for pointing me out to some code mess up I did while copying the codes into the post.