Basic mobile detect by Javascript

In many case we have to detect what user's device is browsing to show UI or content fit it. We can do it easily with some Javascript code below:

Write in your code function call mobileDetect:

 const mobileDetect = function(){
        return {
            detect:function(){
                const uagent = navigator.userAgent.toLowerCase();
                cont phoneList = this.mobiles;
                let ismobile = false;

                for(var d=0; d < phoneList.length; d+=1){
                    if(uagent.indexOf(list[d])!=-1){
                        ismobile = true;
                    }
                }
                return ismobile;
            },

            mobiles:[
                "midp","240x320","blackberry","netfront","nokia","panasonic",
                "portalmmm","sharp","sie-","sonyericsson","symbian",
                "windows ce","benq","mda","mot-","opera mini",
                "philips","pocket pc","sagem","samsung","sda",
                "sgh-","vodafone","xda","palm","iphone",
                "ipod","android"
            ]
        };
    }();
Copy this code


In this function, you can add more device that you want to detect into mobiles array.

Usage: Include your detect function and use it like this:

    if(mobileDetect.detect()){

        alert('You are using a mobile phone.');  

    }else{

        alert('You are using a desktop browser');

    }
Copy this code