0

As soon as the page loads, if you check the console, you see the function fires before I mouseover the elements. If I remove the parameters, then the page waits for me to mouseover the elements, but I lose the dynamic functionality. Am I doing something wrong with passing the elements?

var myList = ["hoverOne", "hoverTwo"];
for(var i=0; i < myList.length; i++){
    document.getElementById(myList[i]).onmouseover=changeImage(myList[i]+"Image");
}
function changeImage(thisDiv){
    console.log(thisDiv);
    //show/hide code here
}

Here is a link to the fiddle I was playing with: http://jsfiddle.net/QtG9P/33/

PaulELI
  • 444
  • 6
  • 16

3 Answers3

1

if you want to maintain the value of i, try it like this:

var myList = ["hoverOne", "hoverTwo"];
for(var i=0; i < myList.length; i++){
    (function(i){
        document.getElementById(myList[i]).onmouseover = function(){
            changeImage(myList[i]+"Image");
        };
    })(i);
}

see it in action here:

http://jsfiddle.net/QtG9P/36/

Zevan
  • 10,097
  • 3
  • 31
  • 48
1

You are calling the function and assigning the return value to the event attribute. You need to wrap the function call in a function expression so that you get a function that you can assign to the attribute.

Also, you need to make a copy of the variable i for each iteration, otherwise the event handler will use the value that i has after the loop. You can do that by wrapping the code inside the loop in an immediately executed function expression:

for(var i=0; i < myList.length; i++){
  (function(i){
    document.getElementById(myList[i]).onmouseover = function(){
      changeImage(myList[i]+"Image");
    };
  })(i);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Change your code like;

myList = ["hoverOne", "hoverTwo"];
for(var i=0; i < myList.length; i++){
    document.getElementById(myList[i]).onmouseover=function (evnt) { changeImage(evnt.srcElement.id); };
}
function changeImage(thisDiv){
    console.log(thisDiv + "Image");
    //show/hide code here
} 

jsfiddle link

umut
  • 1,016
  • 1
  • 12
  • 25
  • Well passing the i variable into the function causes undefined. I think it's because of how closures work. – PaulELI May 17 '14 at 16:16