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

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!

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

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

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


You can always use navigator.appName and if clauses.


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


Fixed script

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(detectwebkit){alert("You're using Chrome, Safari or another Webkit browser")}
if(!opera && NonIE && !detectwebkit){alert('Firefox')}
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.