By the time a click event fires, the loop has already run its course.
Since the variable i
is in global scope, the value referenced from each handler will be the same.
In the example below, notice that each handler references last value in the loop (5):
var mySelect = document.getElementById("mySelect");
for (i = 0; i < nav.children.length; i++) {
nav.children[i].addEventListener("click", function() {
console.log(i);
})
};
<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Hobbies</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
One technique is to use a closure.
For reference, also see Creating Closures in Loops - A Common Mistake.
var nav = document.getElementById("nav");
var mySelect = document.getElementById("mySelect");
var selectOption = function(index) {
return function() {
mySelect.children[index].selected = 'selected';
}
}
for (i = 0; i < nav.children.length; i++) {
nav.children[i].addEventListener("click", selectOption(i));
};
<select name="selectList" id="mySelect">
<option value="one">Home</option>
<option value="two">About</option>
<option value="three">Hobbies</option>
<option value="four">Blog</option>
<option value="five">Contact</option>
</select>
<nav>
<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Hobbies</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
Another technique is to use the let
keyword:
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
var nav = document.getElementById("nav");
var mySelect = document.getElementById("mySelect");
for (i = 0; i < nav.children.length; i++) {
let option = mySelect[i];
nav.children[i].addEventListener("click", function() {
option.selected = 'selected';
});
};
<select name="selectList" id="mySelect">
<option value="one">Home</option>
<option value="two">About</option>
<option value="three">Hobbies</option>
<option value="four">Blog</option>
<option value="five">Contact</option>
</select>
<nav>
<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Hobbies</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>