PaulELI
PaulELI

Reputation: 444

onmouseover function Auto Runs with Parameter

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/

Upvotes: 0

Views: 94

Answers (3)

umut
umut

Reputation: 1026

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

Upvotes: 0

Guffa
Guffa

Reputation: 700572

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);
}

Upvotes: 1

Zevan
Zevan

Reputation: 10235

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/

Upvotes: 1

Related Questions