HASH717 HASH717 - 3 months ago 8
Javascript Question

Mobile device detect, what I'm do wrong?

I use this code to detect mobile devices in order to show download buttons:

function detectDevice() {
var kindle = navigator.userAgent.match(/(Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI)/i) != null;
var android = navigator.userAgent.match(/Android/i) != null;
var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);

if ( kindle)
{
document.getElementById("android_btn").className += " hide";
document.getElementById("ios_btn").className += " hide";
}
else if (iOS)
{
document.getElementById("android_btn").className += " hide";
document.getElementById("kindle_btn").className += " hide";
}
else if (android)
{
document.getElementById("ios_btn").className += " hide";
document.getElementById("kindle_btn").className += " hide";
}
{ // do nothing...show both }
detectDevice();
}}


It doesn't show the right button for the right device it show both buttons for any device.

Answer

Beside missing else statement, you have to bind your function to a onload or onclick events for the code to work.

<body onload="detectDevice()">

EDIT:

example:

<!doctype html>
<html lang="en">
 <head>
  <title>Document</title>
  <style>
  .hide { display: none; }
  </style>
  <script type="text/javascript">
  <!--
    function detectDevice() {
    var kindle = navigator.userAgent.match(/(Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI)/i) ? true : false;
    var android = navigator.userAgent.match(/Android/i) ? true : false;
    var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
    if (kindle)
    { 
        document.getElementById("android_btn").className += " hide"; 
        document.getElementById("ios_btn").className += " hide"; 
    }
    else if (iOS)
    { 
        document.getElementById("android_btn").className += " hide"; 
        document.getElementById("kindle_btn").className += " hide"; 
    }
    else if (android)
    {
        document.getElementById("ios_btn").className += " hide"; 
        document.getElementById("kindle_btn").className += " hide"; 
    }
    else {
        alert("We don't support desktop yet!");
    }
}

  //-->
  </script>
 </head>
 <body onload="detectDevice()">
  <input id="android_btn" type="button" value="Android Download" onclick="">
  <input id="ios_btn" type="button" value="IOS Download" onclick="">
  <input id="kindle_btn" type="button" value="Kindle Download" onclick="">
 </body>
</html>