How to use JavaScript to detect mobile and hand held devices

If you are maintaining separate web pages on your website for visitors viewing your website on their mobile phones or hand held devies then you can use the following JavaScript code to check the visitor’s user agent and direct them to the relevant web pages.

<script type="text/javascript">

var mobile = function(){
return {
detect:function(){
var uagent = navigator.userAgent.toLowerCase();
var list = this.mobiles;
var ismobile = false;
for(var d=0;d<list.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"
]
};
}();

if(mobile.detect()){
// Direct the visitor to the mobile version of your website
}

else{
// Direct the visitor to the desktop version of your website
}

</script>

If you look closely at the code above you can add more user agents with passage of time so your website is up to date with up and coming mobile phones and hand held devices.

Please note if the visitor has disabled JavaScript then the above code will not work.

Let me know if you have any questions/comments