JavaScript Object Detection Targeting IE 6 or IE 7
Today I found myself in an interesting dilemma. I had just spent the morning fine tuning some CSS menu styles, the left nav type with submenus. In my workplace, we only care about IE 6 and Firefox, we keep an eye on Safari, and we’re starting to care about IE 7. My styles were working quite well in all our target browsers, but then I turned my attention to IE 6.
The problem with IE 6 is that it does not support :hover on any element other than an anchor. Knowing I would have to write some JavaScript, I started by using the old document.all test in order to isolate IE; not the best, I know, but that’s another battle for another day.
The problem I encountered was this: the document.all test does not distinguish between IE 6 and IE 7. In other cases, that was fine, but here, I wanted to make sure that IE 7 used the CSS styles without any javascript. So off to google I went.
Unfortunately, I found nothing. After much digging, however, I discovered a combination of tests that solved my problem. First, I came across window.external. Using this isolates IE. The next thing I came across was typeof window.XMLHttpRequest. IE 6 returns undefined, while IE 7 (and Safari, by the way) returns object. (Firefox returns function.)
With these two bits of code, I cobbled together the following, which works well in my work environment:
if (window.external && (typeof window.XMLHttpRequest == "undefined")) {
// javascript targeting IE 6
}
Just change undefined to object to target IE 7. There may be better ways to do this, but since IE 5 is just a bad memory where I work, this solution is fine. My testing was with IE 6 and IE 7 RC.
So far, so good, though I have a feeling there may be a better way. I’d be interested in finding out if anyone has to do something similar in a situation where both IE 6 and IE 7 are target browsers but some javascript is intended for only one or the other.