Enhancing features for mobile with JavaScript

Sometimes specific features and capabilities must be targeted to types of devices for optimal user experience. Progressive enhancement – starting from a basic, widely compatible set of functionality and enhancing it as supported by the current device – is something that’s usually thought of for progressively larger client devices. A common approach to designing with progressive enhancement is to have the most basic features for small devices (smartphones), and progressively add capability for tablets, then desktop browsers.

However, with more and more capable mobile devices, and a desire to achieve a near-native app experience with responsive web solutions, we often find a need to progressively enable features for mobile devices that may not apply on desktop clients. A Javascript technique to achieve this is to use the matchMedia() function.

The matchMedia() API provides a way to find out whether or not a media query currently applies to the page. While the media queries tested don’t have to match media queries in CSS, it’s common to align the CSS and Javascript behaviours for device classes defined with the same view port sizes. The approach we’ve followed is something like this:

  1. Design responsive HTML and CSS to accommodate basic mobile experience (this also helps accommodates “incapable” browsers, including feature phone browsers, browsers with Javascript disabled, and screen-readers)
  2. Use CSS media queries to target progressively more robust HTML and CSS for larger viewports
  3. Use matchMedia() to detect the active media query, and enhance features through Javascript specific to the device class

For example, if we’ve defined our “smartphone” view as having a max-width of 767 pixels, then code to enhance the smartphone view would look something like this:

/* if matchMedia is not supported, then we keep the
   basic experience for the current viewport */
if (window.matchMedia) {
 
    /* matchMedia is supported, so we can use it test if the
       current document matches a specific media query */
    if (window.matchMedia("(max-width: 767px)").matches) {
 
        /* Code to enhance our smartphone view goes here */
    }
}

The matchMedia() API is fairly well supported in current smartphone browsers (see http://caniuse.com/#feat=matchmedia), and in many cases the enhanced features being enabled would also require a relatively recent browser, so testing for matchMedia and only enhancing when it’s supported will often make sense. If you did have a scenario where matchMedia was not supported on a target device, but testing for a media query is needed, then a polyfill is available to add support.

Leave a Reply

Your email address will not be published.

top