Skip to content

Instantly share code, notes, and snippets.

@frankie-loves-jesus
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie-loves-jesus/9603867 to your computer and use it in GitHub Desktop.
Save frankie-loves-jesus/9603867 to your computer and use it in GitHub Desktop.

Detecting mobile devices and tablets in 2014

The mobile world changes almost daily. Expanding on http://scottwb.com/blog/2012/02/23/a-better-way-to-add-mobile-pages-to-a-rails-site/ -- which is sorta old -- what do you guys think of this mobile and tablet detection scheme?

Use case: The mobile and desktop versions of my Rails app are very different. Although they share the majority of views, JS and CSS (using media queries where applicable), there are cases where I need mobile-only and desktop-only views, JS and CSS.

Code changes

All tablets should be treated as mobile.

Above Android tablet thread mentions this for mobile:

  • /iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/

And this for tablet:

  • /ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/

I reckon, however, that only the below should be necessary?

  • /mobile|android|touch|webos|hpwos/

application_controller.rb

def mobile?
  if session[:mobile_override]
    session[:mobile_override] == "1"
  else
    request.user_agent.downcase =~ /mobile|android|touch|webos|hpwos/
  end
end
helper_method :mobile?
layout.html.erb
<% if mobile? %>
  <p>Mobile detected!</p>
<% end %>

application.js

var isMobile = false;

if(/mobile|android|touch|webos|hpwos/i.test(navigator.userAgent.toLowerCase())) {
  isMobile = true;
}

if(isMobile) {
  console.log('Mobile detected!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment