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> 
2
  • you're setting the same image for both device types... and where's blackberry? where's windows mobile? where's symbian? Commented Feb 6, 2015 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. Commented Feb 6, 2015 at 19:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

How does your Android detection code do anything different than what the OP is already using?
Sorry I copied the original and not the actual code I am using. I've corrected the code here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.