JavaScript: Changing location or stylesheet according to device or browser

Developing web applications for mobile phones sometimes brings the need to just create separate content for different devices.

Some time ago I had to create a web app that would look pretty on both, the iPhone and some Windows Mobile based device by HTC! In the end it came out to be simpler just to create another page for the WM device.

Here is a code snippet that I inserted in the header of the index page of the web app:

<script type="text/javascript"> 

 function browser(){
  var browser = navigator.userAgent;

  //Windows Mobile
  if (browser.match("MDA_compact")|| browser.match("MSIE")) {
    window.location.href = "mda/index.html";
 //iPhone & Rest
   document.write('<meta name="apple-mobile-web-app-capable" content="yes" />'
   +'<link rel="apple-touch-icon" href="webapplogo.gif"/>'    
   +'<meta name="apple-mobile-web-app-status-bar-style" content="black" />'
   +'<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />'
   +'<meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" />'
   +'<link href="style.css" rel="stylesheet" type="text/css" />'
   +'<link href="pie.css" rel="stylesheet" type="text/css" />'
   +'<link href="chart.css" rel="stylesheet" type="text/css" />'
   +'<link href="messages.css" rel="stylesheet" type="text/css" />'
   +'<link href="news.css" rel="stylesheet" type="text/css" />'
   +'<link rel="stylesheet" href="stylesheets/glider.css" type="text/css" media="screen" charset="utf-8">');   



You might want to figure out first, how the target device/browser is called. Uncomment the alert(browser) line and get the name. Adapt the browser.match(“Target_browser”) and define what you want to do in that case, e.g. redirect to another page.

Tagged with:

Manoela Ilic

Manoela is the main tinkerer at Codrops. With a background in coding and passion for all things design, she creates web experiments and keeps frontend professionals informed about the latest trends.

Stay up to date with the latest web design and development news and relevant updates from Codrops.

Feedback 3

Comments are closed.