I'd like to know if it's possible to write conditional javascript within a javascript file for Internet Explorer.
i.e. something like this...
if (is IE7) {
do this } else {
do this instead
});
I know I can load a completely different script for IE using conditional comments in the head, but I only want to change a small piece of code and so loading a completely different sheet would be an 'expensive' way to do that.
Despite the fact that this is an answer to the original question, this is NOT what you should do. So don't do it!
Why not work out which browser you are using and store that in a variable in javascript. Then you can have if statemenets and the like in your javascript. e.g. If I am IE then do this, otherwise do that. You get the idea!
Have you seen this? Browser sniffing
The salient bit:
My go-to script for this is PPK's BrowserDetect script. It's lightweight, easily understandable, and doesn't require you to use a library. When it's loaded, you can write code like:
Of course, you should avoid using this at all (reasonable) costs, but there's times where it's cleaner to quarantine IE-specific code away rather than try to hack around IE-specific functions and bugs.
If you are using jquery you code do this
If you want to use jquery, it has a built in browser detect.
http://api.jquery.com/jQuery.browser/
Conditional compilation is exactly what you are looking for.
Not within the JavaScript file directly.
A few alternatives would be:
Using a global variable before the script is loaded to check in your JavaScript file. This is a bit of a hybrid approach and could get messy, but it's guaranteed IE detection.
Or, a more traditional approach using browser or object detection within the JavaScript file.