Category: Javascript

JQuery script to detect Android device

I needed to create a way of detecting whether my application was running on an Android device, as an Android device does not cope with the command ‘window.print(), although the user may still go to the Android browser menu and click print to reveal the same option.

The way I did this was to create the following script:

$(document).ready(function() {
 var ua = navigator.userAgent.toLowerCase();
 var isAndroid = ua.indexOf("android") > -1;
 // If Android then do something
 if (isAndroid) {
    // Find class <strong>.printButton</strong> and add 2 new styles to it
    $(".printButton").css({
        "visibility": "hidden",
        "display": "none"
    });
   }
});

The CSS for .printButton before the script runs looks like this:

.printButton {
 font-size: 16px;
 float: left;
 color: black;
}

After the script runs, .printButton acts like this:

.printButton {
 visibility: hidden;
 display: none;
 font-size: 16px;
 float: left;
 color: black;
}

Link showing the above in action within JSfiddle