0

I am using the below code to detect for mobile and I want to detect either Android only or iOS only. I tested the mobile detect with if( isMobile.iOS() ) alert('iOS'); and it shows the alert.

But I want to display the Android Google Play badge if it is Android and the Apple store badge if it is iOS but for some reason the below code isn't working. Can someone tell me what I am doing wrong?

    var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad /i);
    },
};

if (isMobile.Android()) {
    document.getElementById("googlePlayBadge").innerHTML = "<img src='modal-img/googlePlayBadge.png' alt='Google Play' class='img-responsive' />";
} else {
    if (isMobile.iOS()) 
    document.getElementById("appStoreBadge").innerHTML = "<img src='modal-img/appStoreBadge.png' alt='App Store' class='img-responsive' />";
};

<section class="text-center">
   <div id="appStoreBadge"></div>
   <div id="googlePlayBadge"></div>
 </section>
Alverto
  • 49
  • 1
  • 1
  • 9
  • you're setting the same image for both device types... and where's blackberry? where's windows mobile? where's symbian? – Marc B Feb 06 '15 at 19:36
  • Marc I am only looking for Androind and iOS. The app that I am trying to promote is only for those two and I copied the wrong code. I have correct the correct code I am using here. – Alverto Feb 06 '15 at 19:57

1 Answers1

0

Reliably detecting devices using JS is hard, man. Most sane people will avoid it.

There are libraries that do this, but if that's too much overhead:

var useragent = navigator.userAgent.toLowerCase();

var isAndroid = useragent.indexOf("android") > -1; //&& ua.indexOf("mobile");

if(isAndroid) {

alert('I am an android device');

}

If for some reason you don't care at all about anything other than android or iOS (such as windows phones, blackberries, etc.) you could check if a touch event is available, then check if it's iOS (since that is more reliable), and if it != iOS but does have touch, you can show the play store icon.

sorry, I should also mention that I've used that JS successfully, but it's from here: http://davidwalsh.name/detect-android

jdu
  • 581
  • 2
  • 3