Javascript Browser Window matchMedia() Method detect mobile device

Introduction

Use window.matchMedia() method to detect a mobile device based on the CSS media query.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Detect Mobile Device</title>
</head>//from w w  w .  j av  a 2s.c  o m
<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>



PreviousNext

Related