Q:

How to Detect a Mobile Device in jQuery

0

How to Detect a Mobile Device in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JS matchMedia() Method

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.

The following example will show you how this method actually works:

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

The matchMedia() method is supported in all major modern browser such as Chrome, Firefox, Internet Explorer (version 10 and above), and so on.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the data-id Attribute of an Element Usi... >>
<< How to Set CSS background-image Property Using jQu...