How to detect a mobile device in jQuery?

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

Example-2: Program run on mobile device.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

Supported Browsers:

  • Google Chrome
  • Mozilla Firefox
  • Opera
  • Edge
  • Safari


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.