简体   繁体   中英

jQuery sniff for mobile browsers

How do I sniff for mobile browsers with jquery?

My particular usecase:

I have a game. I want the chatbox to be focused all the time, except in browsers that uses software keyboards (as the keyboard would block the screen).

You could use plain Javascript for detecting mobile devices:

if(!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))){
    //focus input field
    document.getElementById("chattextbox").focus();
}

If you are using jQuery you might use something like that:

$( document ).ready(function() {      
    var isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
    if (!isMobile) {
        //focus input field
        document.getElementById("chattextbox").focus();
    }
});

Here you are testing for the size of the user device. In my opinion this is the better option because you should also style your website with this css media queries and so you have full control over the UI and UX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM