You can detect a mobile device using JavaScript by examining the user agent string provided by the browser.
Here's a simple example of how you can do it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mobile Device Detection</title>
<script>
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
window.onload = function() {
if (isMobileDevice()) {
alert('You are using a mobile device!');
} else {
alert('You are not using a mobile device!');
}
};
</script>
</head>
<body>
</body>
</html>
In this example:
- We define a function isMobileDevice() that checks if the user agent string contains any of the common mobile device identifiers.
- When the window loads, we use this function to determine if the user is using a mobile device or not, and then display an alert accordingly.