Use MDN recommends looking for “Mobi” anywhere in the User Agent to detect a mobile screen size (mobile device) in JavaScript. This will catch some tablets as well, which you need to be ready for and OK with.
navigator.userAgent.indexOf("Mobi") > -1
Read: Browser detection using the user agent
JavaScript detects the mobile screen size
A simple example code detects a mobile device from the browser if the screen size is what you care about:
<!DOCTYPE html>
<html>
<body>
<script>
var isMobile = Math.min(window.screen.width, window.screen.height) < 768 || navigator.userAgent.indexOf("Mobi") > -1;
console.log("is Modible", isMobile)
</script>
</body>
</html>
Output:
JQuery checks if the screen size
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
You can use JavaScript to detect the screen size of a device, including mobile devices. Here’s a simple example of how you can do this:
// Function to detect mobile screen size
function detectMobileScreenSize() {
// Get the width of the screen
var screenWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
// Get the height of the screen
var screenHeight = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
// Check if the screen width is below a certain threshold (for example, 768 pixels)
if (screenWidth < 768) {
// If it is below the threshold, consider it as a mobile device
console.log("Mobile Screen Detected");
return true;
} else {
// If it is equal to or above the threshold, consider it as a non-mobile device
console.log("Non-Mobile Screen Detected");
return false;
}
}
// Call the function to detect mobile screen size
detectMobileScreenSize();
In this script:
window.innerWidth
gives you the width of the viewport.document.documentElement.clientWidth
gives you the width of the document’s client area.document.body.clientWidth
gives you the width of the body element.
Similarly, innerHeight
, documentElement.clientHeight
, and document.body.clientHeight
can be used for detecting the height.
By comparing these values, you can determine whether the screen size is below a certain threshold, which typically indicates a mobile device. In this example, the threshold is set to 768 pixels, but you can adjust it according to your requirements.
Do comment if you have any doubts or suggestions on this JS screen topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version