f w h

Detecting Mobile Browsers in jQuery Without Browser Sniffing

The Concept

Using jQuery’s .css() method, we’ll detect whether a media query has been triggered, and run our code based on that.
The HTML for this is irrelevant. You could use any element for it. You could even just use an element you’re already altering with a media query. For this guide we’ll just use this:


	<div class="hideForMobile"></div>

Now, in CSS, we’ll set a media query to hide this div on mobile:


@media (max-device-width:480px){
  .hideForMobile{display:none;}
}

And now, let’s make the magic happen:


$(document).ready(function(){
  // Grab the value of the display property and store it in a variable
  var mobileTrigger = $('.hideForMobile').css("display");
  // If the display is set to "none", run our code
  if (mobileTrigger=="none"){
    // Code to run
  }
});

Applications

This could be used to run (or prevent running) just about any code that you want. It can also be set up to work with any element and any CSS property, as long as you’ve set that property in your media query.

Update: Vanilla JS

Here is the long overdue update that doesn’t require jQuery:


function isMobile(element_selector, status){
  var e = document.querySelector(element_selector);
  if(getComputedStyle(e).display == status){
    return true;
  } else {
    return false;
  }
}

window.onresize = function(){
  console.log(isMobile('div.hideForMobile', 'none'));
}

The vanilla JS example uses the same HTML and CSS as the jQuery example.