Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Detecting a mobile browser
Detecting mobile browsers in JavaScript is essential for responsive web design and providing device-specific functionality. This can be achieved using the navigator.userAgent property to identify mobile device patterns.
Basic Mobile Detection
The most common approach uses regular expressions to check the user agent string for mobile device identifiers:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mobile Detection</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.result {
font-size: 18px;
font-weight: 500;
margin: 20px 0;
padding: 15px;
border: 2px solid #007bff;
border-radius: 5px;
background-color: #f8f9fa;
}
button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Mobile Browser Detection</h1>
<div class="result" id="result">Click the button to detect device type</div>
<button onclick="detectMobile()">Detect Device</button>
<script>
function detectMobile() {
const isMobile = /iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent);
const resultDiv = document.getElementById('result');
if (isMobile) {
resultDiv.innerHTML = "? This is a mobile device";
resultDiv.style.borderColor = "#28a745";
resultDiv.style.backgroundColor = "#d4edda";
} else {
resultDiv.innerHTML = "? This is not a mobile device";
resultDiv.style.borderColor = "#dc3545";
resultDiv.style.backgroundColor = "#f8d7da";
}
}
</script>
</body>
</html>
Enhanced Mobile Detection Methods
For more comprehensive detection, you can use multiple approaches:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Mobile Detection</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.info-box {
margin: 10px 0;
padding: 10px;
background: #f0f0f0;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Enhanced Mobile Detection</h1>
<button onclick="runDetection()">Run All Detection Methods</button>
<div id="results"></div>
<script>
function detectMobileUserAgent() {
return /iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent);
}
function detectMobileScreen() {
return window.innerWidth <= 768;
}
function detectTouchDevice() {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
function runDetection() {
const userAgentResult = detectMobileUserAgent();
const screenResult = detectMobileScreen();
const touchResult = detectTouchDevice();
const results = document.getElementById('results');
results.innerHTML = `
<div class="info-box">
<strong>User Agent Detection:</strong> ${userAgentResult ? 'Mobile' : 'Desktop'}
</div>
<div class="info-box">
<strong>Screen Size Detection:</strong> ${screenResult ? 'Mobile' : 'Desktop'}
</div>
<div class="info-box">
<strong>Touch Support:</strong> ${touchResult ? 'Supported' : 'Not Supported'}
</div>
<div class="info-box">
<strong>Screen Width:</strong> ${window.innerWidth}px
</div>
`;
}
</script>
</body>
</html>
Comparison of Detection Methods
| Method | Accuracy | Pros | Cons |
|---|---|---|---|
| User Agent | High | Identifies specific devices | Can be spoofed |
| Screen Size | Medium | Responsive to viewport | Tablets may be misclassified |
| Touch Detection | Medium | Detects touch capability | Some laptops have touch screens |
Modern Approach Using Media Queries
For responsive design, CSS media queries combined with JavaScript provide better results:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Media Query Detection</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.device-info {
padding: 15px;
margin: 10px 0;
border-radius: 5px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Media Query Based Detection</h1>
<button onclick="checkDevice()">Check Current Device</button>
<div id="deviceInfo"></div>
<script>
function checkDevice() {
const isMobile = window.matchMedia("(max-width: 768px)").matches;
const isTablet = window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches;
const isDesktop = window.matchMedia("(min-width: 1025px)").matches;
let deviceType = "Unknown";
let bgColor = "#f0f0f0";
if (isMobile) {
deviceType = "Mobile Device";
bgColor = "#d4edda";
} else if (isTablet) {
deviceType = "Tablet Device";
bgColor = "#fff3cd";
} else if (isDesktop) {
deviceType = "Desktop Device";
bgColor = "#d1ecf1";
}
document.getElementById('deviceInfo').innerHTML = `
<div class="device-info" style="background-color: ${bgColor}">
Device Type: ${deviceType}<br>
Screen Width: ${window.innerWidth}px<br>
Screen Height: ${window.innerHeight}px
</div>
`;
}
</script>
</body>
</html>
Key Points
- User Agent Detection: Most reliable for identifying specific mobile devices
- Screen Size: Better for responsive design decisions
- Touch Detection: Useful for enabling touch-specific features
- Media Queries: Best practice for modern responsive web design
Conclusion
Mobile detection in JavaScript can be achieved through multiple methods, each with its strengths. Use user agent detection for device-specific features and media queries for responsive design. Combining approaches provides the most robust solution for different use cases.
