What are the typical reasons Javascript developed on Firefox fails on IE?
Please feel free to update this list if you see any errors/omissions etc.
Note: IE9 fixes many of the following issues, so a lot of this only applies to IE8 and below and to a certain extent IE9 in quirks mode. For example, IE9 supports SVG, <canvas>
, <audio>
and <video>
natively, however you must enable standards compliance mode for them to be available.
##General:
Problems with partially loaded documents: It’s a good idea to add your JavaScript in a
window.onload
or similar event as IE doesn’t support many operations in partially loaded documents.Differing attributes: In CSS, it's
elm.style.styleFloat
in IE vselm.style.cssFloat
in Firefox. In<label>
tags thefor
attribute is accessed withelm.htmlFor
in IE vselm.for
in Firefox. Note thatfor
is reserved in IE soelm['for']
is probably a better idea to stop IE from raising an exception.
##Base JavaScript language:
Access characters in strings:
'string'[0]
isn’t supported in IE as it’s not in the original JavaScript specifications. Use'string'.charAt(0)
or'string'.split('')[0]
noting that accessing items in arrays is significantly faster than usingcharAt
with strings in IE (though there's some initial overhead whensplit
is first called.)Commas before the end of objects: e.g.
{'foo': 'bar',}
aren't allowed in IE.
##Element-specific issues:
Getting the
document
of an IFrame:- Firefox and IE8+:
IFrame.contentDocument
(IE started supporting this from version 8.) - IE:
IFrame.contentWindow.document
- (
IFrame.contentWindow
refers to thewindow
in both browsers.)
- Firefox and IE8+:
Canvas: Versions of IE before IE9 don't support the
<canvas>
element. IE does support VML which is a similar technology however, and explorercanvas can provide an in-place wrapper for<canvas>
elements for many operations. Be aware that IE8 in standards compliance mode is many times slower and has many more glitches than when in quirks mode when using VML.SVG: IE9 supports SVG natively. IE6-8 can support SVG, but only with external plugins with only some of those plugins supporting JavaScript manipulation.
<audio>
and<video>
: are only supported in IE9.Dynamically creating radio buttons: IE <8 has a bug which makes radio buttons created with
document.createElement
uncheckable. See also How do you dynamically create a radio button in Javascript that works in all browsers? for a way to get around this.Embedded JavaScript in
<a href>
tags andonbeforeunload
conflicts in IE: If there's embedded JavaScript in thehref
part of ana
tag (e.g.<a href="javascript: doStuff()">
then IE will always show the message returned fromonbeforeunload
unless theonbeforeunload
handler is removed beforehand. See also Ask for confirm when closing a tab.<script>
tag event differences:onsuccess
andonerror
aren't supported in IE and are replaced by an IE-specificonreadystatechange
which is fired regardless of whether the download succeeded or failed. See also JavaScript Madness for more info.
##Element size/position/scrolling and mouse position:
- Getting element size/position: width/height of elements is sometimes
elm.style.pixelHeight/Width
in IE rather thanelm.offsetHeight/Width
, but neither is reliable in IE, especially in quirks mode, and sometimes one gives a better result than the other.
elm.offsetTop
and elm.offsetLeft
are often incorrectly reported, leading to finding positions of elements being incorrect, which is why popup elements etc are a few pixels off in a lot of cases.
Also note that if an element (or a parent of the element) has a display
of none
then IE will raise an exception when accessing size/position attributes rather than returning 0
as Firefox does.
Get the screen size (Getting the viewable area of the screen):
- Firefox:
window.innerWidth/innerHeight
- IE standards mode:
document.documentElement.clientWidth/clientHeight
- IE quirks mode:
document.body.clientWidth/clientHeight
- Firefox:
Document scroll position/mouse position: This one is actually not defined by the w3c so is non-standard even in Firefox. To find the
scrollLeft
/scrollTop
of thedocument
:Firefox and IE in quirks mode:
document.body.scrollLeft/scrollTop
IE in standards mode:
document.documentElement.scrollLeft/scrollTop
NOTE: Some other browsers use
pageXOffset
/pageYOffset
as well.function getDocScrollPos() { var x = document.body.scrollLeft || document.documentElement.scrollLeft || window.pageXOffset || 0, y = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0; return [x, y]; };
In order to get the position of the mouse cursor,
evt.clientX
andevt.clientY
inmousemove
events will give the position relative to the document without adding the scroll position so the previous function will need to be incorporated:var mousepos = [0, 0]; document.onmousemove = function(evt) { evt = evt || window.event; if (typeof evt.pageX != 'undefined') { // Firefox support mousepos = [evt.pageX, evt.pageY]; } else { // IE support var scrollpos = getDocScrollPos(); mousepos = [evt.clientX+scrollpos[0], evt.clientY+scrollpos[1]]; }; };
##Selections/ranges:
<textarea>
and<input>
selections:selectionStart
andselectionEnd
are not implemented in IE, and there's a proprietary "ranges" system in its place, see also How to get the caret column (not pixels) position in a textarea, in characters, from the start?.Getting the currently selected text in the document:
- Firefox:
window.getSelection().toString()
- IE:
document.selection.createRange().text
- Firefox:
##Getting elements by ID:
document.getElementById
can also refer to thename
attribute in forms (depending which is defined first in the document) so it's best not to have different elements which have the samename
andid
. This dates back to the days whenid
wasn't a w3c standard.document.all
(a proprietary IE-specific property) is significantly faster thandocument.getElementById
, but it has other problems as it always prioritizesname
beforeid
. I personally use this code, falling back with additional checks just to be sure:function getById(id) { var e; if (document.all) { e = document.all[id]; if (e && e.tagName && e.id === id) { return e; }; }; e = document.getElementById(id); if (e && e.id === id) { return e; } else if (!e) { return null; } else { throw 'Element found by "name" instead of "id": ' + id; }; };
##Problems with read only innerHTML:
IE does not support setting the innerHTML of
col
,colGroup
,frameSet
,html
,head
,style
,table
,tBody
,tFoot
,tHead
,title
, andtr
elements. Here's a function which works around that for table-related elements:function setHTML(elm, html) { // Try innerHTML first try { elm.innerHTML = html; } catch (exc) { function getElm(html) { // Create a new element and return the first child var e = document.createElement('div'); e.innerHTML = html; return e.firstChild; }; function replace(elms) { // Remove the old elements from 'elm' while (elm.children.length) { elm.removeChild(elm.firstChild); } // Add the new elements from 'elms' to 'elm' for (var x=0; x<elms.children.length; x++) { elm.appendChild(elms.children[x]); }; }; // IE 6-8 don't support setting innerHTML for // TABLE, TBODY, TFOOT, THEAD, and TR directly var tn = elm.tagName.toLowerCase(); if (tn === 'table') { replace(getElm('<table>' + html + '</table>')); } else if (['tbody', 'tfoot', 'thead'].indexOf(tn) != -1) { replace(getElm('<table><tbody>' + html + '</tbody></table>').firstChild); } else if (tn === 'tr') { replace(getElm('<table><tbody><tr>' + html + '</tr></tbody></table>').firstChild.firstChild); } else { throw exc; }; }; };
Also note that IE requires adding a
<tbody>
to a<table>
before appending<tr>
s to that<tbody>
element when creating usingdocument.createElement
, for example:var table = document.createElement('table'); var tbody = document.createElement('tbody'); var tr = document.createElement('tr'); var td = document.createElement('td'); table.appendChild(tbody); tbody.appendChild(tr); tr.appendChild(td); // and so on
##Event differences:
Getting the
event
variable: DOM events aren't passed to functions in IE and are accessible aswindow.event
. One common way of getting the event is to use e.g.elm.onmouseover = function(evt) {evt = evt||window.event}
which defaults towindow.event
ifevt
is undefined.Key event code differences: Key event codes vary wildly, though if you look at Quirksmode or JavaScript Madness, it's hardly specific to IE, Safari and Opera are different again.
Mouse event differences: the
button
attribute in IE is a bit-flag which allows multiple mouse buttons at once:- Left: 1 (
var isLeft = evt.button & 1
) - Right: 2 (
var isRight = evt.button & 2
) - Center: 4 (
var isCenter = evt.button & 4
)
The W3C model (supported by Firefox) is less flexible than the IE model is, with only a single button allowed at once with left as
0
, right as2
and center as1
. Note that, as Peter-Paul Koch mentions, this is very counter-intuitive, as0
usually means 'no button'.offsetX
andoffsetY
are problematic and it's probably best to avoid them in IE. A more reliable way to get theoffsetX
andoffsetY
in IE would be to get the position of the relatively positioned element and subtract it fromclientX
andclientY
.Also note that in IE to get a double click in a
click
event you'd need to register both aclick
anddblclick
event to a function. Firefox firesclick
as well asdblclick
when double clicking, so IE-specific detection is needed to have the same behaviour.- Left: 1 (
Differences in the event handling model: Both the proprietary IE model and the Firefox model support handling of events from the bottom up, e.g. if there are events in both elements of
<div><span></span></div>
then events will trigger in thespan
then thediv
rather than the order which they're bound if a traditional e.g.elm.onclick = function(evt) {}
was used."Capture" events are generally only supported in Firefox etc, which will trigger the
div
then thespan
events in a top down order. IE haselm.setCapture()
andelm.releaseCapture()
for redirecting mouse events from the document to the element (elm
in this case) before processing other events, but they have a number of performance and other issues so should probably be avoided.Firefox:
Attach:
elm.addEventListener(type, listener, useCapture [true/false])
Detach:elm.removeEventListener(type, listener, useCapture)
(type
is e.g.'mouseover'
without theon
)IE: Only a single event of a given type on an element can be added in IE - an exception is raised if more than one event of the same type is added. Also note that the
this
refers towindow
rather than the bound element in event functions (so is less useful):Attach:
elm.attachEvent(sEvent, fpNotify)
Detach:elm.detachEvent(sEvent, fpNotify)
(sEvent
is e.g.'onmouseover'
)
Event attribute differences:
Stop events from being processed by any other listening functions:
Firefox:
evt.stopPropagation()
IE:evt.cancelBubble = true
Stop e.g. key events from inserting characters or stopping checkboxes from getting checked:
Firefox:
evt.preventDefault()
IE:evt.returnValue = false
Note: Just returningfalse
inkeydown
,keypress
,mousedown
,mouseup
,click
andreset
will also prevent default.Get the element which triggered the event:
Firefox:
evt.target
IE:evt.srcElement
Getting the element the mouse cursor moved away from:
evt.fromElement
in IE isevt.target
in Firefox if in anonmouseout
event, otherwiseevt.relatedTarget
Getting the element the mouse cursor moved to:
evt.toElement
in IE isevt.relatedTarget
in Firefox if in anonmouseout
event, otherwiseevt.target
Note:
evt.currentTarget
(the element to which the event was bound) has no equivalent in IE.
Check also for commas such as these or similar if any in your code
var o={
'name1':'value1',
'name2':'value2',
}
the last comma (following value2) will be tolerated by Firefox, but not IE
If you stick to using jQuery or YUI as your post is tagged, you should have minimal differences between browsers...that's what the frameworks are for, to take care of these cross-browser differences for you.
For an example, look at the quirksmode DOM traversal page, according to it IE doesn't support most things...while true, the frameworks do, for example IE doesn't support elem.childElementCount
, but in jQuery: $(elem).children().size()
works to get this value, in every browser. You'll find there's something in the library to handle 99% of the unsupported cases across browsers, at least with script...with CSS you might have to move to plugins for the library, a common example of this is to get rounded corners working in IE...since it has no CSS support for such.
If however you start doing things directly, like document.XXX(thing)
, then you're not in the library, you're doing javascript directly (it's all javascript, but you get the point :), and this might or might not cause issues, depending on how drunk the IE team was when implementing that particular function.
With IE you're more likely to fail on styling coming out right than raw javascript issues, animations a few pixels off and that sort of thing, much more-so in IE6 of course.