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;
  //alert(browser);

  //Windows Mobile
  if (browser.match("MDA_compact")|| browser.match("MSIE")) {
    window.location.href = "mda/index.html";
  }
 //iPhone & Rest
  else{
   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">');   
   }
  }

 browser();

</script>

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.

Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Subscribe and get our Collective newsletter twice a tweek.

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 in the loop: Get your dose of frontend twice a week

👾 Hey! Looking for the latest in frontend? Twice a week, we'll deliver the freshest frontend news, website inspo, cool code demos, videos and UI animations right to your inbox.

Zero fluff, all quality, to make your Mondays and Thursdays more creative!

Feedback 3

Comments are closed.