Reputation: 41
I know this is simple, but I can't seem to get this to work. When the page loads, it checks the browser. if its chrome I want it to hide a div, but show it if its anything else.
it detects the browser ok, since i checked using alerts, but the hiding bit doesn't. Can you help
function browserTest() {
var browser = /Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent);
if (browser) {
document.getElementById("chromeBox").style.visibility = "hidden";
//alert("chrome");
}
else {
document.getElementById('chromeBox').style.visibility = 'visible';
//alert("not chrome");
}
}
Upvotes: 1
Views: 122
Reputation: 41
Thanks a lot everyone. its working now, just needed to call the function after the div. I'm new to javascript, so I'm still making basic errors like this.
Thanks
Upvotes: 1
Reputation: 25682
It seems that we cant figure out what happens with your DOM so here is an example: http://jsfiddle.net/mgechev/uwc3B/2/
Here is the code:
JavaScript
function browserTest() {
var browser = /Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent);
if (browser) {
document.getElementById("chromeBox").style.visibility = "hidden";
//alert("chrome");
}
else {
document.getElementById('chromeBox').style.visibility = 'visible';
//alert("not chrome");
}
}
browserTest(); //should be called on DOM ready
HTML
<div id="chromeBox">
It's not Chrome!
</div>
CSS
#chromeBox {
width: 100px;
height: 100px;
background: #ccc;
position: absolute;
}
You should call browserTest
at the end of the body or on DOM ready.
Upvotes: 1
Reputation: 12815
You may have few problems here:
1) browserTest
is executed before div is actually load (if it is executed in <head>
section with code like below, for example):
<head>
<script>
function browserTest() { .... }
browserTest(); - div is not loaded here yet and getElementById will return nothing.
</script>
To fix this - put that script section after chromeBox div html markup or execute browserTest in onload event (that will guaranty that div is already loaded and getElementById will find it):
<head>
<script>
function browserTest() { .... }
</script>
....
</head>
<body onload="browserTest()">
....
2) Check if your div really has an ID chromeBox
. IDs are case sensitive, so document.getElementById("chromeBox")
will not find <div id="ChromeBox">
Remember that visibility:hidden will make a div invisible, but space for it will be still reserved. Maybe you should better use style.display = "none"/style.display = "block"
Also, learn how to use developer tools. All browsers have it. For firefox you may need to install Firebug. Just call it using F12 and check console to see if any error is shown there.
Upvotes: 1