How to Redirect Mobile Devices With JavaScript and CSS
Learn How to Redirect Mobile Devices With JavaScript and CSS. 1.JavaScript Method, 2. CSS @media Method. Fast solution for web developers.
With the growth of tablet and smartphone users, it becomes essential to give users the option to switch from the desktop version to the mobile version. It is straightforward to do with a little JavaScript code or with the help of CSS @media queries. Let’s discuss each of them separately.
JavaScript Method
This method requires a little JavaScript code in the <head> section. Replace the placeholder URL with your mobile site address and insert the following JavaScript code in the <head> section. The domain will redirect to the mobile URL when the viewport width is equal to or less than 699px:
redirect with window.innerWidth
<script>
if (window.innerWidth <= 699) {
window.location.href = "https://w3docs.com/";
}
</script>Not all mobile devices support JavaScript. Also, include a link on your website so users can manually switch to the mobile version. Ensure your mobile site does not redirect back to the desktop version to avoid infinite redirect loops.
You can also use the "user-agent" approach to achieve similar results. The advantage of "user-agent" detection is that you can target specific devices. Note: User-agent sniffing is generally discouraged today due to spoofing and high maintenance costs. Viewport-based detection is preferred.
Here’s the "user-agent" detection for iPhone and iPod:
redirecting with userAgent example
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
window.location.replace("https://w3docs.com/");
}CSS @media Method
You can use CSS @media queries to apply different styles based on the device. Instead of the obsolete handheld media type, modern practice uses @media rules within your CSS or <style> tags:
load CSS depending on screen, example
<link rel="stylesheet" href="screen.css" media="screen"/>
<style>
@media (max-width: 768px) {
/* Mobile-specific styles */
}
</style>The CSS @media rule is a built-in method used to apply styles based on the viewport size. It does not require a separate mobile site. All you need is a single webpage with responsive styles: the default styles for desktop monitors and @media queries for smartphones.