Using JQuery to Detect If on a Mobile Phone

JQuery and/or JavaScript have no native mechanism to determine whether a page is loaded on a mobile phone or not. However, CSS media queries offer this capability. I found the following nice trick on stackoverflow to utilize media queries to help JS/JQuery applications to determine whether they run in a mobile.

First, insert an arbitrary div somewhere in the body of your HTML document such as:

<div id=”mobileDetector”></div>

Then, add the following CSS:

@media only screen and (max-width: 480px) {
#mobileDetector { display: none; }

(Note: You can also use the width 767px or so to also capture tablets).

Finally, the following JQuery function can be used to determine if on a mobile or not:

(function($) {
  $.isMobile = function() { 
      return $('#mobileDetector').css('display') === 'none'; 
}) (jQuery);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s