0

Possible Duplicate:
Javascript closure inside loops - simple practical example

I am (quite obviously) a beginner in javascript. I am attempting to understand why, when using a for loop and calling an event handler ala

http://jsfiddle.net/Yw5Uj/

var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');
var content = document.getElementById('content');
var contentSections = content.getElementsByTagName('div');


for(i =0; i < contentSections.length; i++) {
    contentSections[i].style.display = 'none';
}

for(i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = function() {
         contentSections[i-1].style.display = 'block'
    }
}

I only get the last iteration of the loop. How would I call a function to act on each of the links in the navLinks array as they are moused over?

There are many questions on this, but often times they are a bit too complicated for me to understand.

Community
  • 1
  • 1
Squadrons
  • 2,467
  • 5
  • 25
  • 36

2 Answers2

1

Try the following

var makeFunction = function(i) {
  return function() { contentSections[i-1].style.display = 'block'; };
};

for(var i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = makeFunction(i);
}

What's throwing you off is the lifetime semantics of i. In Javascript there is only one i defined for the current function (and without the use of var it's likely in the global scope). So every function assigned to onmouseover is using the same i variable which has the final value of navLinks.length.

My solution works because it uses function scope to create a new i for every iteration of the loop.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

Updated example here.

function handleMouseOver(i) {
    return function () {
        for (var j = 0; j < navLinks.length; j++) {
            contentSections[j].style.display = 'none';
        }
        contentSections[i].style.display = 'block';
    }
}

for(i =0; i < navLinks.length; i++) {
    navLinks[i].onmouseover = handleMouseOver(i);
}
Paul Grime
  • 14,970
  • 4
  • 36
  • 58