CodeinWP CodeinWP

7 JavaScript Differences Between Firefox & IE

Please note that this is an older article that discusses JavaScript issues in Internet Explorer versions 6 & 7, along with Firefox versions 2+ & 3.0.

Although the days of long and tedious code branches to target specific browsers in JavaScript are over, once in a while it’s still necessary to do some simple code branching and object detection to ensure that a certain piece of code is working properly on a user’s machine.

In this article, I’ll outine 7 areas where Internet Explorer and Firefox differ in JavaScript syntax.

1. The CSS “float” property

The basic syntax for accessing a specific css property for any given object is object.style.property, using camel casing to replace a hyphenated property. For example, to access the background-color property of a <div> whose ID is “header”, we would use the following syntax:

document.getElementById("header").style.backgroundColor= "#ccc";

But since the word “float” is already reserved for use in JavaScript, we cannot access the “float” property using object.style.float. Here is how we do it in the two browsers:

The IE Syntax:

document.getElementById("header").style.styleFloat = "left";

The Firefox Syntax:

document.getElementById("header").style.cssFloat = "left";

2. The Computed Style of an Element

JavaScript can easily access and modify CSS styles that have been set on objects using the object.style.property syntax outlined above. But the limitation of that syntax is that it can only retrieve styles that have been set inline in the HTML or styles that have been set directly by JavaScript. The style object does not access styles set using an external stylesheet. In order to access an object’s “computed style”, we use the following code:

The IE Syntax:

var myObject = document.getElementById("header");
var myStyle = myObject.currentStyle.backgroundColor;

The Firefox Syntax:

var myObject = document.getElementById("header");
var myComputedStyle = document.defaultView.getComputedStyle(myObject, null);
var myStyle = myComputedStyle.backgroundColor;

3. Accessing the “class” Attribute of an Element

As is the case with the “float” property, our two major browsers use different syntax to access this attribute via the getAttribute method in JavaScript.

The IE Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");

The Firefox Syntax:

var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");

This syntax would also apply using the setAttribute method.

See a demo page that demonstrates these two different syntaxes

4. Accessing the “for” Attribute of the <label> Tag

Similar to number 3, we have different syntax to access a <label> tag’s “for” attribute in JavaScript.

The IE Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");

The Firefox Syntax:

var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("for");

5. Getting the Cursor Position

It would be rare that you would want to find the cursor position of an element, but if for some reason you need to, the syntax is different in IE and Firefox. The code samples here are fairly basic, and normally would be part of a much more complex event handler, but they serve to illustrate the difference. Also, it should be noted that the result in IE will be different than that of Firefox, so this method is buggy. Usually, the difference can be compensated for by getting the “scrolling position” — but that’s a subject for another post!

The IE Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.clientX;
myCursorPosition[1] = event.clientY;

The Firefox Syntax:

var myCursorPosition = [0, 0];
myCursorPosition[0] = event.pageX;
myCursorPosition[1] = event.pageY;

6. Getting the Size of the Viewport, or Browser Window

Sometimes it’s necessary to find out the size of the browser’s available window space, usually called the “viewport”.

The IE Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = document.documentElement.clientWidth;
myBrowserSize[1] = document.documentElement.clientHeight;

The Firefox Syntax:

var myBrowserSize = [0, 0];
myBrowserSize[0] = window.innerWidth;
myBrowserSize[1] = window.innerHeight;

7. Alpha Transparency

Okay, this is not a JavaScript syntax issue — alpha transparency is set via CSS. But when objects fade in and out via JavaScript, this is done by accessing CSS alpha settings, usually inside of a loop. The CSS code that needs to be altered via JavaScript is as follows:

The IE Syntax:

#myElement {
  filter: alpha(opacity=50);
}

The Firefox Syntax:

#myElement {
  opacity: 0.5;
}

So, to access those values via JavaScript, we would use the style object:

The IE Syntax:

var myObject = document.getElementById("myElement");
myObject.style.filter = "alpha(opacity=80)";

The Firefox Syntax:

var myObject = document.getElementById("myElement");
myObject.style.opacity = "0.5";

Of course, as mentioned, normally the opacity/alpha would be changed in the midst of a loop, to create the animating effect, but this simple example clearly illustrates how it’s done.

Are There Other Differences?

These are some of the differences I’ve personally come across either in development or research, but I’m sure there are others. Leave a comment if you think I’ve left out an important one, and I’ll try to update this list, or else do a “Part 2” post.

36 Responses

  1. Nice find!

    I personally use jQuery and don’t run into these issues.

    A good reference none the less.

    • JAson says:

      The way that css display is returned is different when reading classes (with jQuery even) – IE reads as [DISPLAY: none] while FF displays more like we all right our css – display:none;

      cost time and money, and cost others time and money, when you try to be different. (<- ok, that was uncalled for – sorry to those who try to reinvent languages that exists and call themselves compatible.) – I LOATHE debugging js

      • Jazz says:

        JAson, you’re right. Nonconformity is so dangerous! If everybody did everything the same way, all the time, the world would work so much more smoothly!

        I have a great idea. Why don’t we just use one programming language for everything? From optimizing the kernel all the way up to scripting the UI! That way nobody will be doing anything “different” and therefore dangerous. After all, it would cost us so much more time and money if we keep using different tools for different tasks! Who wants a whole workshop when you can just buy a Leatherman which does everything?!

        Conformity is awesome! At least, that’s what all my fellow developers are telling me here in the Camazotz IT department. So it must be true!

    • anjay says:

      If you pre-load images and load them dynamically before into your interface, only the first ‘window.onload’ works if you refresh the page all your images disappear in IE only FF works correctly. addd your own images to this script and modify the imgNames array
      var imgNames = [“Refresh”, “Telephone”, “StaffPortal”, “SRContractsdb”, “StatApp”, “MapApp”, “AdminForms”, “Calendar”, “ARVTdb”, “Exit” ];

      var initMenu= function(){

      var table=document.createElement(‘table’)
      table.id=”myTable”
      table.align=’center’

      var imgNames = [“Refresh”, “Telephone”, “StaffPortal”, “SRContractsdb”, “StatApp”, “MapApp”, “AdminForms”, “Calendar”, “ARVTdb”, “Exit” ];
      var imgObjects = [];

      var objBotMenu=document.getElementById(‘botmenu’)
      var tbody = document.createElement(“tbody”);
      var row = document.createElement(“tr”)
      var td = document.createElement(“td”)
      td.id=’mid’

      row.appendChild(td);
      tbody.appendChild(row);
      table.appendChild(tbody);
      //document.body.appendChild(table);

      objBotMenu.appendChild(table);

      for (var i = 0; i < imgNames.length; i++){
      imgObjects[i] = new Image();
      imgObjects[i].src = 'imgs/'+ imgNames[i] + '.png';
      imgObjects[i].onload = function(){
      for (var i = 0; i < imgNames.length; i++){
      td.appendChild(imgObjects[i]);
      imgObjects[i].className="imgIcon";
      var imgleft=imgObjects[i].left
      imgObjects[i].onmouseover=function() {// function number 1
      var params = findPos(this);
      var capsLayer= document.createElement("span")
      capsLayer.style.position="absolute";
      capsLayer.style.left= params[0]-310 ;
      capsLayer.id='capsLayerId';
      capsLayer.innerHTML= ''+eval(imgNames[i])+'';
      td.appendChild(capsLayer);

      var capsLayer=
      this.position="absolute";

      //this.parentNode.verticalAlign="top"//**************position

      if(!this.nextSibling){
      this.className="thumbImg";

      }else{

      this.nextSibling.className="mideuim"//function code /#/1
      }

      if(!this.previousSibling){
      this.className="thumbImg"

      }else{

      this.previousSibling.className="mideuim"

      }

      this.className="thumbImg"

      this.onmouseout=function() {
      var capsLayer=document.getElementById('capsLayerId');
      if(capsLayer)
      capsLayer.parentNode.removeChild(capsLayer)
      this.className="imgIcon";

      // this.parentNode.verticalAlign="top";//******************position

      if(!this.nextSibling){this.className="imgIcon"

      }else{
      this.nextSibling.className="imgIcon"//function code /#/1

      }

      if(!this.previousSibling){
      this.className="imgIcon"

      }else{
      //function code /#/2
      this.previousSibling.className="imgIcon"

      }

      };

      };

      }

      }
      }
      };
      function findPos(obj) {
      var curleft = curtop = 0;
      if (obj.offsetParent) {
      while (obj.offsetParent) {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
      }
      }
      return [curleft,curtop];
      }

      window.onLoad=initMenu

      body{scroll-bars: none}
      #myTable { bottom:50px ; left:1%;width:98%%;background-color: #FFFFCC; position:absolute;text-align:center;height:18%;vertical-align:middle;left:25%; top:80%}
      .imgIcon {width:50px;height:50px;}
      .thumbImg {width:150px;height:150px;}
      .mideuim {width:100px;height:100px;}
      #mid{vertical-align:bottom;valign:middle}

      Add row

      menu

    • Christian Kolbas says:

      New to posting, so hello all. I am not able to get the className property of an object in IE11. Anyone see this issue yet? Works fine in IE10..

      Problem:

      
      var Name = $get('&lt%=txtLeadName.ClientID %&gt');
      Name.className = 'tablefontyellow';
      
      
      it doesn't error, but just sets the className too ''(empty)
      
      
      Any help would be greatly appreciated!

  2. IE / FF

    Position:
    offset / layer (offsetX / layerX ….)
    page / ??? (PageX, PageY)

    Event..
    ??? / currentTarget
    returnValue / preventDefault
    srcElement / target
    fromElement, toElement / relatedTarget
    cancelBubble / stopPropagation

    has more …

  3. All the more reasons to use a JS library like jQuery which normalizes all this.

  4. Good, informative article. As a nitpick I would have to argue that these aren’t really JavaScript language differences, but differences in the DOM API implementations of different browsers.

    And of course, using a framework (Prototype, jQuery, Dojo, YUI, etc.) will help you not have to worry about these differences and not waste time worrying about these annoying differences.

    For the always-comprehensive list of differences: http://quirksmode.org/compatibility.html

  5. Matt Kruse says:

    #3 and #4 are misleading. Your examples simply point out a problem with IE’s getAttribute() method, which internally returns a DOM property rather than an actual attribute. In Firefox, you also need to use element.className and element.htmlFor if you want to access the DOM property value, but since its getAttribute() is not broken, you can pass it the correct attribute name.

    #6 is also misleading because it depends on whether IE is in standards mode or not. In quirks mode, your IE solution will not work. And in FF, your IE solution works just fine.

    You should also be careful to mention browser versions. IE6 != IE7 != IE8.

  6. tz says:

    Um, I think you pasted the wrong line in example 1:

    to access the background-color property of a whose ID is .header., we would use the following syntax:
    document.getElementById(“header”).style.borderBottom= “1px solid #ccc”;

    Anyway, nice article!

  7. fearlex says:

    Awesome list, i’m so used to frameworks, that i forgot a lot of basic stuffs like this ones. Bookmarked, thx.

  8. David Hucklesby says:

    Do you know if the “style.filter” property works in IE 8?

    I know Microsoft changed the CSS “filter” to “-ms-filter” and altered the syntax, but I’ve not been able to find if this affects scripting.

  9. @tz:

    Thanks for catching that. I had originally used the border property while writing the examples, but changed it later.

    @Matt Kruse:

    Thank you for clarifying the issue with getAttribute. My list was very basic though, so I suppose, yes, it may be a little misleading.

  10. Keloran says:

    document.getElementById(), when used on form elements in IE returns the name, not the id [affects 6 ]

    so if yo have

    getElementById(“stuff”) will return the form element not the div

  11. Benni Austin says:

    You left out a big one that’s had me caught up at least once. That would be IE’s ability to grab an element by id, without using getElementById(). This issue hung me up when I had a div with an id of “totalPrice”, and used the same “totalPrice” as a variable name in the js on the page. IE thought I was trying to access the element when I called the variable.

  12. Ed Stivala says:

    Sounds like another seven reason for not gong near Firefox to me.
    I guess it is too much to hope for that all the volunteers get together and sort out Firefox so that it works
    in the same way as IE… Still you can always hope :-)

  13. willwagner says:

    Two things that have bitten me because firefox is a little bit more lax on syntax, and that cause errors in IE (and should probably in firefox)

    Objects with trailing commas

    In firefox, it won’t complain if you do this:

    var foo = {
    field1: 0,
    field2: 1, // notice the comma
    };

    Indexing a character in a string with a subscript

    var foo = “abc”;
    var bar = foo[1]; // should be charAt()

  14. There is an issue with the class property… in IE you have to access it with the .className notation

    document.getElementBYId(“myid”).className = “my_class”;

  15. Ramesh.S says:

    Working of javascript code according to the different browsers like IE,Firefox…
    is given in your website, is very helpful for me to enhance my knowledge in javascript. I really got high benefit from this.

    I also highly expect more new programming tips better than this in your website in future days.
    keep it up
    By
    Ramesh.S,
    Software Engineer,
    Chennai,
    TamilNadu
    India.

  16. Ajay Singh says:

    Good Post
    was really helpful :P

  17. Ken Blackman says:

    Sorry, I’m missing a subtlety here. On #3, getting (or in my case setting) the class, what exactly is the diff between FF and IE? If someone could put just a few more words to it, it would help a lot! Thanks.

  18. @Ken Blackman:

    The difference is that if you use getAttribute to access the “class” attribute of any given element, you use different syntax. In IE, you use the syntax “className”, whereas in FF you use just plain “class”. I’ve set up a demo page that might make it more clear:

    getAttribute Demo.

  19. Henry Truong says:

    I will introduce the more 2 differences between FireFox and IE for which I bumped into it when I worked with my projects:

    1. Strict Syntax Validation
    FireFox, Safari, Google Chrome validates syntax very strict. The following example doesn’t work correctly without “px”:

    myDiv.style.width = (myDiv.offsetWidth – 50) + ‘px’;

    Whereas, IE and Opera automatically add “px” if developer overlooks this string.

    2. Look up text value of parent node. IE and FireFox treats it in different ways.

    if(navigator.appName == “Microsoft Internet Explorer”) //IE
    {
    selectedValue = document.getElementById(myID).parentNode.innerText;
    }
    else if(navigator.appName == “Netscape”) //Firefox
    {
    selectedValue = document.getElementById(myID).parentNode.childNodes.item(1).innerHTML;
    }

  20. James says:

    Thank you. This post was incredibly useful.

    I really wish all browsers shared the same javascript. I have wasted years of my life fixing scripts for IE!

  21. g says:

    thanks for the article…. not everyone cares to use frameworks (as more power can be achieved in direct js most of the time), but it helps to remember these key points ;)

    • Nathan says:

      Thank you g, I totally agree that tools like JQuery are useful, but they can never be as powerful as building JS from the ground up. I prefer to have my own library of scripts for firefox/ie compatibility (and I add to it all the time). I feel as though tools like JQuery dull a programmer’s ability to think with logical creativity when confronted with a problem that the framework cannot handle.

  22. Galeel says:

    for #4 and #5; when i run the demo link in IE8, i am getting displayed “null” then “test” as like FF.

    Please mention the IE version in your post

  23. gaurab says:

    document.getElementById(“supplier_no”).value= values_array[0];

    this piece of .js code works perfect in IE but not in firefox, get error as getElementById returns null.

    what to do… plz. email me with some tips: gaurab_bas@yahoo.com

  24. Demiurg says:

    In IE you can’t use variable named ‘item’ – it’s reserved keyword.
    In FF you can.
    Be careful.

  25. Rohit Patidar says:

    This doesn’t work for Firefox :-
    1. var myCursorPosition = [0, 0];
    2. myCursorPosition[0] = event.pageX;
    3. myCursorPosition[1] = event.pageY;

    Please could you suggest me anything else.

    Actually my problem is that i have to give ajax call when window closes. I used window.onbeforeunload .But problem is it is called when page is refreshed. So i want that only and only when my browser is closed then in window.onbeforeunload i should get position of browser close button and i will handle the call.

  26. Jasmine says:

    Nice list of Js differences… I am getting crazy trying to fix the getElementById problem… hope your tips there can help me. Thanks anyway.

  27. Van says:

    Interesting me, here you study subtleties of writing of scripts that they worked in different browsers, but nobody swears at the authors of these browsers.
    In fact it through their fault the whole world has complications in debugging of scripts.
    The internet had good web-sites a long ago, if the inventors of browsers did not interfere with programmers, and helped them.

  28. aub says:

    Go to this page with Firefox and IE. Tell me why the differences occur.

    http://www.aubfmet.ms11.net/AFMsites.html

    • The only major difference I see is the default color of the link text. Is that what you’re referring to? Every browser chooses their own color for that. They’re not required to choose the same one.

      Also, that page does not have a doctype. But when I added the doctype, that didn’t seem to change much other than some alignment.

      • aub says:

        Thank you for looking. I was unable to get firefox to recognize the color red in the top table. I worked with tools/options/content / color and it was not responding. Now mysteriously it is working correctly.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).