jQuery: individuare i principali dispositivi mobile

jQuery: individuare i principali dispositivi mobile

Con jQuery possiamo individuare i principali dispositivi mobile.

La soluzione รจ la seguente:


"use strict";

var MobileDetect = {
    body: $( "body" ),
    android: undefined,
    blackberry: undefined,
    ios: undefined,
    iemobile: undefined,
    operamini: undefined,
    mobile: undefined,

    isAndroid: function() {
        if ( this.android === undefined ) {
            if ( ( this.android = ( navigator.userAgent.match( /Android/i ) !== null ) ) ) {
                this.body.addClass( "android" );
            }
        }
        return this.android;
    },
    isBlackBerry: function() {
        if ( this.blackberry === undefined ) {
            if ( ( this.blackberry = ( navigator.userAgent.match( /BlackBerry/i ) !== null ) ) ) {
                this.body.addClass( "blackberry" );
            }
        }
        return this_blackberry;
    },
    isiOS: function() {
        if ( this.ios === undefined ) {
            if( ( this.ios = ( navigator.userAgent.match( /iPhone|iPad|iPod/i ) !== null ) ) ) {
                this.body.addClass( "ios" );
            }
        }
        return this.ios;
    },
    isIEMobile: function() {
        if ( this.iemobile === undefined ) {
            if ( ( this.iemobile = ( navigator.userAgent.match( /IEMobile/i ) !== null ) ) ) {
                this.body.addClass( "iemobile" );
            }
        }
        return this.iemobile;
    },
    isOperaMini: function() {
        if ( this.operamini === undefined) {
            if ( ( this.operamini = ( navigator.userAgent.match(/Opera Mini/i ) !== null ) ) ) {
                this.body.addClass( "operamini" );
            }
        }
        return this.operamini;
    },
    isMobile: function() {
        if ( this.mobile === undefined ) {
            if( this.mobile == ( MobileDetect.isAndroid() || MobileDetect.isiOS() || MobileDetect.isBlackBerry() || MobileDetect.isIEMobile() || MobileDetect.isOperaMini() ) ) {
                this.body.addClass( "mobile" );
            }
        }
        return this.mobile;
    }
};

Esempio d'uso:


$(function() {
    MobileDetect.isMobile();
});

Torna su