Skip to content

JavaScript detect mobile or tablet | HTML Example code

The Simplest way is using vanilla JavaScript navigator API to detect mobile or tablet in HTML webpage. You have to regex (regular expression) in the query.

You can also use a 3rd party library such as wurfl.io:- https://web.wurfl.io/#wurfl-js

if (WURFL.is_mobile === true && WURFL.form_factor === "Tablet") {
    // targetSmartPhoneDevices();
}

Example of JavaScript detect mobile or tablet

Using a console log to print message, IT will print message for tablet and mobile.

You can use it detect if the device is ONLY tablet or mobile.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        const userAgent = navigator.userAgent.toLowerCase();

        var isMobile = /iPhone|Android/i.test(navigator.userAgent);
        console.log(isMobile);

        const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent);
             console.log(isTablet)

        if(isMobile) {
            console.log("Mobile")
        }else if(isTablet){
            console.log("Tablet")
        }
   

    </script>
</head>
<body>

</body>
</html>

Output:

JavaScript detect mobile or tablet

All major browser provides a very useful API to know the user’s device and the browser details.

window.navigator.userAgent

Do comment if you have better example or doubts or suggestions this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “JavaScript detect mobile or tablet | HTML Example code”

  1. I have a set of media queries with revised css for each tablet and mobile. Each query changes several proprties in several classes. How do I use the results of this script to activate the correct media query?

    Can i set a css variable and test it in the query statement? Or is there another solution?

    Thanks for your help.

Leave a Reply

Your email address will not be published. Required fields are marked *