Detect mobile or touch devices on both server and client

There is a better maintained regular expression to be found on detectmobilebrowsers.com.

Although it's tempting flirt with detecting mobile/touch devices with CSS media queries or Javascript feature detection alone, this approach will be painful when heavily customizing a feature beyond just tweaking the looks. Eventually you will want want the same detection logic to be available on both server and client side.

This card shows how to get a Ruby method touch_device? for your Rails views and a method TouchDevice.isPresent() for your Javascripts.

Note that we are detecting touch devices by grepping the user agent, and the keyword list we are sniffing for sure is lacking many unpopular phones.


In your ApplicationHelper:

def touch_device?
  user_agent = request.headers["HTTP_USER_AGENT"]
  user_agent.present? && user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i
end

In your layout:

%html
  %body{ :class => 'touch_device' => ('true' if touch_device?)}

In your application.js:

var TouchDevice = (function() {

  var presence = null;

  function isPresent() {
    if (_.isNull(presence)) {
      presence = $('body').is('.touch_device');
    }
    return presence;
  }

  return { isPresent: isPresent };

})();
Henning Koch Over 12 years ago