I want to use the jQuery hover method for rollovers above a base area image map that incorporates numerous odd shapes, so that rolling over each exact shape triggers an image swap, as well as an .innerhtml swap in a separate text block. I started with a placeholder “zero” image that’s completely transparent, then swap to a png above the live image map area on rollover, then back to the zero image on rollout.
So, code for one area map zone looks something like the below. Here, areamapImage1 corresponds to a coordinate zone of the base image.
$('#areamapImage1').hover(
function() {
$('#imageSwap').attr('src','images/image1.png');
},
function() {
$('#imageSwap').attr('src','images/image0.png');
});
This works like a charm, as long as I declare each hover function explicitly. For 20 images, that generates a ton of unnecessary code; obviously, it screams for arrays and a loop. So... should be simple to fill two arrays: one for the image map areas and one for the swap images. Console logging after the loop gives me what I expect, but the hover function doesn’t work. As I’ve never done much of anything in JS, I strongly suspect there’s a brain-dead operator error here, either due to JS/jQuery syntax or scope. As far as I can tell though, the variables should be available to the hover function(?). Both arrays return strings. jQuery has a syntax that puts selectors in single quotes; when I tried setting up the imageArea array to include the quotes explicitly, the hover threw a very strange syntax error, so I assume jQuery just uses regular strings instead.
Thanks for any suggestions!
$(document).ready(function() {
// image preload
var imageSource = [];
imageSource[0] = 'images/image0.png' //load 0 position with "empty" png
var imageAreas = [];
// area map and image array fill
for (var i=1; i<21; i++) {
imageSource[i] = 'images/image' + i + '.png'; //
imageAreas[i] = '#areamap_Image' + i;
$(imageAreas[i]).hover( // hover function
function() {
$('#imageSwap').attr('src',imageSource[i]);
},
function() {
$('#imageSwap').attr('src','images/image0.png');
});
};
});