How to detect a mobile device in jQuery?
Last Updated :
16 Apr, 2019
We can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and easiest way to detect mobile devices.
Syntax:
window.matchMedia();
Example-1: Program run on desktop.
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
jQuery Detect Mobile Device
</ title >
</ head >
< body >
< script >
if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
document.write("This is a mobile device.");
} else {
// The viewport is at least 768 pixels wide
document.write("This is a tablet or desktop.");
}
</ script >
</ body >
</ html >
|
Output:
Example-2: Program run on mobile device.
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
jQuery Detect Mobile Device
</ title >
</ head >
< body >
< script >
if (window.matchMedia("(max-width: 767px)").matches)
{
// The viewport is less than 768 pixels wide
document.write("This is a mobile device.");
} else {
// The viewport is at least 768 pixels wide
document.write("This is a tablet or desktop.");
}
</ script >
</ body >
</ html >
|
Output:
Supported Browsers:
- Google Chrome
- Mozilla Firefox
- Opera
- Edge
- Safari
Share your thoughts in the comments
Please Login to comment...