How to detect mobile devices on webpage

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

With the rise of mobile and responsive web design, we need to detect when mobile devices are accessing our webpage and change the layout accordingly.   In responsive design, we typically use CSS Media query to detect viewport width or device width.

Sometimes CSS Media query is not sufficient and you want to determine viewport and device width via javascript.   Then you can use response.js.

Device Detection using User Agent string

Sometimes you need even more fine grain detection.  Some retina display ipads can have higher resolution than older desktop monitors.  So you might need to do some device detection to detect for tablets or smart phone.  One way to do this detect the “user agent string”.  This can be done at server side such as PHP as in …

<?php 
 if ( stripos($_SERVER['HTTP_USER_AGENT'],'android') !== false ) {
    echo 'is android device';
 } else {
    echo 'not android device';
 }
?>

Or javascript such as …

<script>
 if ( navigator.userAgent.toLowerCase().indexOf("android") >= 0 ) {
    alert("is android");
 } else {
    alert("not android");
 }
</script>

List of User Agent Detection strings

You can find a list of user agent detection string on MobileESP.

Device Detection Scripts

MobileESP is a nice device detection script.  At the time of this writing, it includes detection scripts using javascript, ruby, php, java, asp, and python.

DetectMobileBrowsers.com is a collection of open-source mobile device detection scripts.

HandsetDetection.com is a commercial set of detection scripts.

 


Related Posts

Tags

Share This