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.

Write the URL of your website and insert the following JS code in it. 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.

You can use the "user-agent" approach as well to achieve the same results. The advantage of "user-agent" detection is that you 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

You can use the CSS @media method for the detection of browsers. 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"/>

The CSS @media rule is a built-in method used to detect mobile browsers. It displays CSS styles based on the browser window size. This does not require a separate mobile site. All you need is two style sheets within one webpage: the “screen” media type (desktop monitors) and the “handheld” media type (smartphones).