...

View Full Version : Help - Using Objects with If/then Statements



daled1
09-26-2011, 07:35 AM
Hi, I am trying to detect a users browsers and output a different code based on browser.

I found this code online that uses the object detection method and it works. When I document.write(BrowserDetect.browser) it outputs Chrome, (which is what I am using). The code can be found here: http://www.quirksmode.org/js/detect.html

So I can't understand why the following code does not work? It ouputs the "not" in the else statement.

I believe that BrowserDetect is an object and the .browser at the end is a property of the object.

Can one not make an object a variable? or make an object a string?

oh and BTW there is a bunch of javascript that creates the browserdetect object that can be found on the site above, but I thought it would be too unwieldy to post here. Thanks.

The following script outputs:
Chrome Not Working

<script type="text/javascript">

document.write(BrowserDetect.browser);

var browser="BrowserDetect.browser";

if(browser=="Chrome")
{
document.write(" Working");
}
else
{
document.write(" Not working");
}
</script>

ironboy
09-26-2011, 07:44 AM
It doesn't work because you are not calling the BrowserDetect object asking for its property browser, instead you are just assigning "BrowserDetect.browser" as a string value to the variable browser. Remove the quotation marks and it should work:
var browser = BrowserDetect.browser;

if(browser=="Chrome")
{
document.write("<b>Good morning</b>");
}
else
{
document.write("<b>not</b>");
}
(Also be sure to include PPK:s detection code before your own code...)

daled1
09-26-2011, 07:48 AM
Ah...right. Thanks it works!

Philip M
09-26-2011, 08:06 AM
To detect Chrome:-


var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') >-1;
alert (is_chrome);
All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

Kor
09-26-2011, 03:39 PM
You are dealing with a rather academical problem. Usually no one needs to detect browsers; the coders need, most of the time, to detect if a browser has implemented a method or another, thus usually they detect the existence of that method, not of the browser's type.

After all, the browser's type is, most of the time, irrelevant. Same as the color of a cat, as long as she catches mice :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum