I essentially know nothing when it comes to Javascript, so any help is appreciated.
When a user is on a mobile phone, I want a div to popup with a link to my mobile website. Naturally, I don’t want the popup to show when the user is on their desktop.
My issue is that I can’t get the javascript to apply the css.
Here’s the javascript that I’m using.
<script type="text/javascript">
var isMobile = navigator.userAgent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i);
if(isMobile){
document.getElementById('mobile').style.display = 'block';
}
else{
document.getElementById('mobile').style.display = 'none';
}
;
</script>
This is the div:
<div id="mobile" style="left:116px; position: absolute; top: 106px;">
If you would like to visit our mobile website optimized for your device, click <a href="http://m.website.org">here</a>.</div>
Any help is appreciated. I’ve tried figuring it out myself, but I’ve hit a road block.
If you have a better, completely separate solution, that is welcome as well.
I think you’re problem is that the javascript is being executed before the DOM (the HTML) is loaded and ready for manipulation. That code must fire after the window’s
onloadevent fires. As usual, I’d recommend using jQuery library but I’ll give an example that doesn’t use it just so you don’t need to include it – you just have to be careful that there isn’t other javascript that needs to be ran when the event fires; its easy to accidently override it.Also, I would recommend keeping the div hidden by default and use JS to show it when needed.
See it here
http://jsfiddle.net/vmuX8/1/
This script is safe to use with other scripts on the same page.
In my example, I declare an anonymous (nameless) function which gets ran instantly after it is declared. That is to scope the variables inside of it so that no global variable is ever affected (except the window.onload function).