Well I know… JavaScript is a big quirk in general due to the browser incompatibilities.

When you build an event and attach it to a object in DOM by:

Javascript [Show Plain Code]:
  1. obj.onclick = handlerFunctionName;

and then you have a function declared like this:

Javascript [Show Plain Code]:
  1. function handlerFunctionName(ev)
  2. {
  3.     var element = ev.srcElement ? ev.srcElement: ev.target; // for compatibility between IE and FF
  4. }

IE fails to execute that, where FireFox runs fine.
A quick fix for that is:

Javascript [Show Plain Code]:
  1. function handlerFunctionName(ev)
  2. {
  3.    ev = ev ? ev: event;
  4.    var element = ev.srcElement ? ev.srcElement: ev.target; // for compatibility between IE and FF
  5. }

Variable event is automagically created in IE but it doesn’t exist under FF, while under FF event is passed to the function and under IE it isn’t.

Another bump I’ve hit today was when I tried to selectively remove some images from a form based on their className.
A simple for loop which one may think will work will actually leave behind some of the images that it should remove.
Here is how not to do this:

Javascript [Show Plain Code]:
  1. for(i=0; i< images.length;i++)
  2. {
  3.    if(images[i].className=="deleteMe")
  4.    {
  5.       myForm.removeChild(images[i]);
  6.    }
  7. }

The reason for that is when you remove something from the images array you will skip one place ahead in the for loop iteration.
I’ve found some examples how to remove all child elements, but what I needed was to remove only some, so here is how I did it. It actually loops a bit more times than the previous example, as it’s iterating through all child elements in myForm

Javascript [Show Plain Code]:
  1. var myForm = document.getElementById("myForm");
  2. var i = 0;
  3. while( myForm.childNodes[i])
  4. {
  5.    if(myForm.childNodes[i].className == "deleteMe")
  6.    {
  7.       myForm.removeChild(myForm.childNodes[i]);
  8.    }
  9.    else
  10.    {
  11.       i++;
  12.    }
  13. }

Leave a Reply