How to Redirect Mobile Devices With JavaScript and CSS

With the growth of the tablet and smartphone users, it becomes essential to give the users the option to switch the desktop version to the mobile version. It is straightforward to do with a little JavaScript code or with the help of CSS @media method. Let’s discuss each of them separately.

JavaScript Method

This method requires a little JavaScript code into the <head> section.
  1. Write the URL of your website.
  2. Insert the following JS code on your website, the domain will redirect to Mobile URL when the screen width is equal or less than 699px.
<script type="text/javascript">
if (screen.width <= 699) {
     document.location = "";
Not all mobile phones support JavaScript Method. Also, include a link on your website so as the users go to the mobile version.

We can use with "user-agent" approach. The advantage of "user-agent" detection is that we can customize for many devices.

Here’s the "user-agent" detection for iPhone and iPod:

<script type="text/javascript">
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

CSS @media Method

We can use the CSS @media method for the detection of browsers.

We should implement two CSS @media - "screen" and "handheld" in the <head> section:

<link rel="stylesheet" href="screen.css" media="screen"/>
<link rel="stylesheet" href="handheld.css" media="handheld"/>

Do you find this helpful?

Related articles