How to Detect a Mobile Device in JavaScript

You can simply use the JavaScript window.matchMedia()method to detect a mobile device based on the CSS media query. This is the best and most reliable way to detect mobile devices.

About matchMedia()
The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

Syntax
matchMedia(mediaQueryString)
Return value
A new MediaQueryList object for the media query. Use this object's properties and events to detect matches and to monitor for changes to those matches over time.

Example
To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the matches property, which will be true if the document meets the media query's requirements.
<script>
$(document).ready(function(){
    if(window.matchMedia("(max-width: 767px)").matches){
        // The viewport is less than 768 pixels wide
        alert("This is a mobile device.");
    } else{
        // The viewport is at least 768 pixels wide
        alert("This is a tablet or desktop.");
    }
});
</script>
Note: The matchMedia()method is supported in all major modern browser such as Chrome, Firefox, Internet Explorer (version 10 and above), and so on.