Onevent Function Call passed Calculated Arguments

Here is a small snip-it that I’m using to colour lines of a table as a user rolls over them.

function colour(){
var rows = document.getElementsByTagName(“tr”);

for(i=0;i<rows.length;i++){
    var defaultColor = rows[i].style.backgroundColor;
        rows[i].onmouseover = change;
 rows[i].onmouseout = function()
                                     {this.style.backgroundColor=defaultColor;};
}

}

My problem arises on the onmouseout event. Instead of calling an unnamed function, I would rather call a named function outside of ‘colour’. However, I’m having much trouble passing arguments and don’t know how to do this - or whether I can at all.

I would like the code to look something like this:

rows[i].onmouseout = changeBack(defaultColor);

But I know that this would initiate ‘changeBack’ right then and there, and it wouldn’t have access to defaultColor.

How do I get around this?

rows[i].onmouseout = function() {changeBack(defaultColor)};

Wow. I feel slightly stupid, but glad, that the solution was so simple.

Many thanks felgall

Will that though retain the defaultColor value for each row?

Actually, It does.
It’s working for me.

I edited the code a bit to look like this:

rows[i].onmouseout = function() {changeBack(this, defaultColor)}

function changeBack(object, color){object.style.backgroundColor = color;}

and it’s working.

That’s good news. When the assigned function is inside the loop, it’s tempting to mistakenly believe that the inner contents of the function retain state-based info from outside.

As a separate function that is invoked with parameters, there is less opportunity for misunderstandings to occur.