Have been struggling with Javascript closure for a while trying to wrap brain around function scopes, but I think they're wrapping around me instead. I've looked at a number of posts (Nyman's was the most helpful) but obviously still don't get it. Trying to run a loop over the hover method in jQuery. Need hover functions to ultimate trigger more than one action each, but would be happy to get them working with a single image swap each for now.
$(document).ready(function() {
imageSource = [];
imageSource[0] = 'images/img0.png' //load 0 position with "empty" png
imgArea = [];
for (var i=1; i<11; i++) {
(function( ){ //anonymous function for scope
imageSource[i] = 'images/img' + i + '.png';
imgArea[i] = '#areamap_Img' + i;
// running console.log here gives expected values for both
$(imgArea[i]).hover( //imgArea[i] (selector) works correctly here
function() {
$('#imgSwap').attr('src',imageSource[i]); // imageSource[i] is undefined here
},
function() {
$('#imgSwap').attr('src','images/img0.png');
});
})(); // end anonymous function and execute
}; // for loop
});
Tried the idea of using an anonymous function for scoping from another jQuery post. Seems to work OK but throws an undefined for the array value in the first hover function, I guess because it's an inside function (hardcoded image sources work correctly there).