I am learning about closures and have the basics on what they are and how they work.
I got the following code from MDN and know what the solution is since it's in the same article. I just don't get how this is possible:
<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
I know the section of code that needs change for this to work is:
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
How is it that at the end of the loop the text being pointed to is: Your age (you must be over 16)
for all elements?
I can follow the code and see that the loop successfully loops through the elements correctly but I can't get my head around how is it that the last item pointed to for all elements at the end is Your age ...
since it saves each one individually with the onfocus = funtion()...
and what ever item.help
is at the time is passed in and saved.
Any step by step explanation would greatly help in me understanding what is going on.