The Wayback Machine - https://web.archive.org/web/20230330135329/https://www.geeksforgeeks.org/how-to-detect-a-mobile-device-in-jquery/
Skip to content
Related Articles
Open in App
Not now

Related Articles

How to detect a mobile device in jQuery?

Improve Article
Save Article
Like Article
  • Last Updated : 16 Apr, 2019
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!