Detect device in jQuery

Detect device in jquery

Sometime we need to detect device in jQuery to identify the screen, To add some extra or different logic according to the requirement.

5 ways to detect the mobile Devices in jQuery

Solution 1:- Using navigator userAgent.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  // mobile device code
}

Solution 2:- Using window matchMedia method

$(function() {      
    let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

    if (isMobile) {
        //Conditional script here
    }
 });

Solution 3:- Using window screen width

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
if(mobile){
	// mobile device
}

Solution 4:- Using CSS and js. Add css on the element to the particular with and then check element visible or not using js.

/* CSS for smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}


In jQuery/JavaScript file:

$( document ).ready(function() {

    if( $('#some-element').css('display')=='none') {
     	// logic for the mobile device   
    }
 });

Solution 5:- Using window innerWidth method

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device detect
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device detect
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device detect
        return "md"
    } else {
        // Large Device detect
        return "lg"
    }
};

var device = getBrowserWidth();
if(device === "xs"){
  // code for your logic
}

Related Post setTimeout() and setInterval in jQuery

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top