The Problem
As we've seen throughout our study of CSS and JavaScript, Internet Explorer and Netscape render some things very differently. Often there is no good workaround.
These cases might be able to benefit from making two external stylesheets -- one for IE and one for Netscape. We can then use JavaScript to determine what browser the viewer is using and direct them to the appropriate stylesheet.
The first step in doing this is to make the styling for each browser. Put the IE style rules on one external CSS file and the Netscape style rules on another. In this example I'll be calling these "iestyle.css" and "netstyle.css".
The Redirect
The JavaScript to redirect a browser to the appropriate stylesheet is pretty simple. First we detect which browser is being used and then use "document.write()" to write the <link> tag that loads the external stylesheet.
<head>
<script language="JavaScript">
if (navigator.appName == "Microsoft Internet Explorer"){
Redirect For IE Will Go Here
}
else{
Redirect For Netscape Will Go Here
}
</script>
</head>
Above is the JavaScript browser detection part of the scheme. Now I'll add the "document.write()s" that will link to the appropriate .css file.
<head>
<script language="JavaScript">
if (navigator.appName == "Microsoft Internet Explorer"){
document.write("<link rel=\"stylesheet\" href=\"iestyle.css\" type=\"text/css\">);
}
else{
document.write("<link rel=\"stylesheet\" href=\"netstyle.css\" type=\"text/css\">);
}
</script>
</head>
What we've done is to use JavaScript to write the <link> tag as opposed to coding one in manually. But, there's more to it than that. Notice that the .css files in the HREFs are different. This is how we link to one .css file over another.
Another thing to keep in mind is the use of the escape character (\) when making quotes. We've covered this already, but it's worth noting again. When double quotes are nested in a "document.write()", "alert()", etc., we need to tell the browser whether nested quotes are part of the code or a part of the string.
The escape character (\) tells the browser that the character that follows, double quotes in this case, are to be rendered as part of the string and not to be considered part of the code.
Practice doing this by making a page that has a blue background in Internet Explorer and a green background in Netscape.
Back To Beginning JavaScript Index
|