Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onmouseover for the last of several generated divs will not work in IE

I have a JavaScript function:

function addTool(id, text, tool, pic) {
   var container = getById('infobox');
   var origimg = getById('tempimg').src;
   container.innerHTML += "<div id='" + id + "' class='toolText'>" + text + "<br><img      class='toolImg' src='img/tools/" + tool + "'></div>";
   getById(id).setAttribute('onMouseOver', "mOver('"+ id +"', '" + pic + "');");
   getById(id).setAttribute('onMouseOut', "mOut('"+ id +"', '" + origimg + "');");
   getById(id).setAttribute('href', 'javascript:mClick(id);');
}

Which generates several divs, using this code:

addTool("1p", "Bar", "tool1.jpg", 'img/p&g-part-2_skiss1-2.jpg');
addTool("2p", "Tube", "tool1.jpg", 'img/p&g-part-2_skiss1-2.jpg');
addTool("3p", "Rotating", "tool1.jpg", 'img/p&g-part-2_skiss1-2.jpg');

The mouse events work fine in all major browsers except IE. It seems that all divs except the last will have the mouse event in lowercase which will have the mouse event exactly as written, with upper case letters.
All mouse events will fire except for the last div, even if I write onmouseover instead of say ONmouseOVER, which works fine on all except the last.

like image 347
Glinkis Avatar asked Nov 13 '22 20:11

Glinkis


1 Answers

Do not use setAttribute to add events. Use attachEventListener/addEvent

The problem you have is adding the elements to the div. You are basically wiping it away each time when you are adding the new elements. That is bad. You should be using appendChild to add new content to the div.

Basic idea:

function attachEvent(elem, eventName, fn) {
    if ( elem.attachEvent ) {
        elem.attachEvent( 'on' + eventName, fn);
    } else {
        elem.addEventListener( eventName, fn, false );
    }
}


function addTool(text, message) {

   var container = document.getElementById('infobox');
   var newTool = document.createElement("a");
   newTool.innerHTML = text;
   newTool.href="#";
   var myClickFnc = function(e) {
       alert(message);
       return false;
   }
   attachEvent(newTool, "click", myClickFnc);
   container.appendChild(newTool);
}

addTool("cat","meow");
addTool("dog","bark");
addTool("pig","oink");

running example

like image 132
epascarello Avatar answered Dec 21 '22 04:12

epascarello