How to detect Mobile & Retina Devices: 8 Techniques

How to detect Mobile & Retina Devices: 8 Techniques
by Janeth Kent Date: 02-07-2013 web development retina mobile devices techniques


In order to serve mobile-optimized content, you need to detect which visitors are coming from mobile devices and which aren’t.

Here we have list 8 method to detect mobile browsers so you can chose the best suitable to your needs, and give your user the best experience possible.

#1 PHP User Agent

We can test the user agent comparing with a list of known mobile user agents so you can redirect the user to a different version, add a new cookie, set a global variable to be used in your CMS, set a HTML class or anything else you may want to do.

The PHP code itself is quite simple.We'll use the preg_match() function to compare current browser with an array of mobile browsers:

<?php      
//Here is the known mobile user agents list      
$mobiles = array("iPhone","iPod");        
foreach( $mobiles as $mobile ) {          
if( preg_match( "#".$mobile."#i", $_SERVER['HTTP_USER_AGENT'] ) ) {              
//Ok, this is a mobile browser, let's redirect it!              
header('Location:http://mobile.mysite.com/');               
exit();         
}}  
?>

You can disable this test, via Cookie setting a link to yoursite?nomobile=1 then you can test this var before doing the redirection part:

<?php      
//let's check if we have a get or post or cookie set to nomobile      
if ( isset( $_REQUEST['nomobile'] ) && true == $_REQUEST['nomobile'] ) {          
//now we check if we have set the cookie, so we don't need the "get" in the URL all the time          
if ( ! isset($_COOKIE['nomobile']) ) {              
setcookie("nomobile", 1, (time()+60*60*24*30) );          
}
} else {          
//nevermind, let's check if current browser is a mobile            
//Here is the known mobile user agents list          
$mobiles = array("iPhone","iPod");            
foreach( $mobiles as $mobile ) {              
if( preg_match( "#".$mobile."#i", $_SERVER['HTTP_USER_AGENT'] ) ) {                  
//Ok, this is a mobile browser, let's redirect it!                  
header('Location:http://mobile.mysite.com/');                  
 exit();              
}          
}      
}  
?>

#2 JavaScript User Agent

The JS is more suitable for places where you have little or no control on the server side code, or you want to do something specific (like a landing page).

Moreover, the JS code is quite limited because you need to load the entire site before doing the redirection.

So, here is an example:

<script type="text/javascript">      
var mobiles = array["iPhone", "iPod"];//mobile devices      
var i;        for(i=0;i< mobiles.lenght;i++){         
 //testing if the RE matches the mobile agents          
var er = new RegExp(mobiles,"i");          
if( er.test( navigation.userAgent ) ) {              
window.location = "http://mobile.mysite.com/" ;          
}}  
</script>

#3 WordPress code

WordPress actually has an internal mobile sniffing tool so you’ll have a global variable to tell you if the current user is an iPhone or not (and a few other browsers).

Here is an example:

<?php      
function load_my_styles() {          
global $is_iphone; //loading global var here          
if( $is_iphone ) {              
wp_enqueue_style( 'iphone-style', get_stylesheet_directory_uri() . '/ iphone-style.css');          
} else {              
wp_enqueue_style('normal-style', get_stylesheet_directory_uri() . '/ style.css');         
 }  
 }     
 add_action( "wp_enqueue_scripts", "load_my_styles" );  
?>

#4 WordPress Plugins

Here are some options: 

 

 

 

#5 HTML Code for Retina

This is a simple way to be done in your

, while you’re calling your styles:

<link rel="stylesheet" type="text/css" src="css/common_style.css" />  
<link rel="stylesheet" type="text/css" src="css/retina.css" media="only screen and (-webkit-min-device-pixel-ratio:2)" />

#6 Media queries

The media queries allow you to conditionally apply styles.

/* Smartphones (portrait and landscape) ----------- */  
@media only screen   and (min-device-width : 320px)   
and (max-device-width : 480px) {  /* Styles */  }    /*
Smartphones (landscape) ----------- */  
@media only screen   and 
(min-width : 321px) {  /* Styles */  }   
 /* Smartphones (portrait) ----------- */ 
@media only screen   and (max-width : 320px)
 {  /* Styles */  }    
/* iPads (portrait and landscape) ----------- */  
@media only screen   and (min-device-width : 768px)  
 and (max-device-width : 1024px) {  /* Styles */  }   
 /* iPads (landscape) ----------- */  
@media only screen   and (min-device-width : 768px)   
and (max-device-width : 1024px)   and (orientation : landscape) {  /* Styles */  }    
/* iPads (portrait) ----------- */  
@media only screen   and (min-device-width : 768px)   
and (max-device-width : 1024px)   and (orientation : portrait) {  /* Styles */  }    
/* Desktops and laptops ----------- */  @media only screen   and (min-width : 1224px) {  /* Styles */  }   
 /* Large screens ----------- */  
@media only screen   and (min-width : 1824px) {  /* Styles */  } 
/* iPhone 4 ----------- */  @media  only screen and (-webkit-min-device-pixel-ratio : 1.5),  
only screen and (min-device-pixel-ratio : 1.5) {  /* Styles */  }

If you want to target only retina devices you can try:

@media only screen and (-webkit-min-device-pixel-ratio:2){  }

#7 Media Queries via JavaScript

An obscure technique perhaps...

You can test media queries using JavaScript, and if returns true, for example, you could conditionally change classes, change image src attributes, redirect your page.

<script type="text/javascript">      
//JS version for the retina query      
var modern_media_query = window.matchMedia( "screen and (-webkit-min-device-pixel-ratio:2)");        
if( modern_media_query.matches ){          
//DO ALL THE THINGS HERE      }  
</script>

#8 Htaccess code

The idea is similar to the first PHP method.

RewriteCond %{HTTP_USER_AGENT} “ipod|iphone|ipad|blackberry”[NC]  
RewriteCond %{REQUEST_URI} ^/$  
RewriteRule ^ http://m.yoursite.com%{REQUEST_URI} [R,L]

 

 
by Janeth Kent Date: 02-07-2013 web development retina mobile devices techniques hits : 8417  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

JavaScript Formatting Date Tips

Something that seems simple as the treatment of dates can become complex if we don't take into account how to treat them when presenting them to the user. That is…

How to set up your Android phone: learn how to get your new phone up and running

If you've just bought a great new Android phone, you'll want to start using it as soon as possible. You'll see that it's not hard to get the initial set-up and…

Top tools for UX design and research

This article is a compilation of the "ux tools" I have tested in recent years. I've separated the tools by categories, although I recommend you to take a look at all…

How to make a multilingual website without redirect

Today, we're going to talk about how to implement a simple language selector on the basic static website, without the need of any backend or database calls or redirection to…

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

Bootstrap 5 beta2. What offers?

Since the release of the Bootstrap 4 is three years, in this article we will present what is new in the world’s most popular framework for building responsive, mobile-first sites.…

Graphic design and its impact on Web Development

In today's article we will explain the concept of graphic design, its fundamentals and what it brings into web development. Graphic design is applied to everything visual, believe or not,…

Creating simple CSS spinner-loader

In today's article we will show you how to animate a basic loader that spins when some predefined action is defined, such as loading an image. That can be used…

Understanding LCP, CLS, FID. All about Core Web Vitals in Google Search Console

A few months ago we talked about certain Google metrics that were displayed in Search Console. The reason for writing another post on this topic is that Google has changed…

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration