I'm trying to wrap my head around a closure that I found, I understand closures on a surface level but I'm having trouble trying to understand the following.
I have a div with 3 input fields and a gray box above all of them like this: https://i.stack.imgur.com/RRYP8.png and when an input field's focus
event is fired with jQuery, the grey box should change to a specific text depending on the input field.
Below is the following code to achieve this:
function main() {
var tipText = [{
'id': '#email',
'tip': 'Only @pocketbook.com addresses allowed.'
}, {
'id': '#name',
'tip': 'Your name must be capitalized.'
}, {
'id': '#employeeId',
'tip': 'Employee IDs are found on the back of your badge.'
}];
function tipCallback(tip) {
return function() {
$('#tip').text(tip);
};
}
function getTip() {
for (var i = 0; i < tipText.length; i++) {
var item = tipText[i];
$(item.id).focus(tipCallback(item.tip));
}
}
getTip()
}
$(document).ready(main);
I know that we need a closure since the state is not being persisted in the for loop, but I still can truly understand it.