PDA

View Full Version : How can JavaScript be used to display things differently in two different browsers?



kitson
03-13-2012, 08:00 AM
Hey everyone, I started programming and was wondering how JavaScript can be used to display things differently in two different browsers? Thanks for all help!

molendijk
03-13-2012, 05:00 PM
You'll need browser detection. What browsers do you have in mind?
Arie Molendijk.
===

keyboard
03-14-2012, 03:52 AM
Two more things:

One- Do you need to be able to detect diferent browser versions

Two-

You can always use navigator.appName and if clauses.

Example:


<script type="text/javascript">
var browser=navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
alert("Browser is IE");
}
</script>


Keyboard1333

Fixed script

molendijk
03-14-2012, 11:53 AM
That code is not correct. It'll produce Browser is IE for all browsers.
You could try something like this (the alerts are just examples; you can add other alerts, experiment with it):

<script type="text/javascript">
var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/; //detect ie6
var detectie6=document.all && !window.XMLHttpRequest; //detect IE6
var IE7 = false /*@cc_on || @_jscript_version == 5.7 @*/; //detect ie7
var gteIE7 = false /*@cc_on || @_jscript_version >= 5.7 @*/; //detect ie-versions 7 and higher
var isMSIE = /*@cc_on!@*/false; //detect ie
var NonIE = /*@cc_on!@*/true; //detect non-ie
var detectwebkit=navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1; //detect WebKit browsers (Safari, Chrome etc)
var opera=window.opera
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
/* With this, IE versions can be captured by conditionals like if (ieversion>=8), if (ieversion>=7), if (ieversion>=6), if (ieversion>=5), if (ieversion==8) etc. */
}

if(detectie6){alert("You're using IE6")}
if (ieversion>=6){alert("You're using IE6 or higher")}
if(opera){alert('opera')}
if(detectwebkit){alert("You're using Chrome, Safari or another Webkit browser")}
if(!opera && NonIE && !detectwebkit){alert('Firefox')}
</script>
You should be aware of the fact that browser detection using javascript may sometimes produce false results (although I think the script above is rather safe).
If you want to distinguish between IE-versions, you can use conditional statements; it's better.
===
Arie.