I have a setup function that runs onload to add some behaviours to elements. The setup function passes arguments to the mouseover event but those arguments are being changed during the for loop because they are local references.
function setupAreas( image, map, lots ) {
// obj is a simple wrapper for doc.getElementById
var image = obj(image); // image for imagemap
var map = obj(map); // imagemap element
var areas = map.getElementsByTagName('area');
for (var i in areas) {
var area = areas[i]; // imagemap area element
area.id = area.alt;
}
for (var lot_id in lots) {
if (lot_id != 'Lot No' && lot_id != '') {
var area = document.getElementById(lot_id);
if (!area || !area.coords) {
alert('no map coords for lot '+lot_id);
} else {
var coords = area.coords.split(",");
//alert('tag: '+area.tagName+' id: '+lot_id+' area: '+area);
var details = lots[lot_id];
if (details) {
// setup mouseover call with complete details of area
area.onmouseover = function(){ showLot(lot_id, area, coords, details, image, map, areas, lots) };
... snip ...
The problem is that because of the for loop the references lot_id and area are changed on each iteration. The result is the mouseover event for any element gives the lot_id and area of the last area only.
I don’t want or need jQuery for this. A simple JS solution that doesn’t pollute the global namespace is preferred.
Try surrounding the contents of your for loop in a closure:
let me know how that works out
EDIT: You don’t have to surround the whole loop actually, you could just surround the line that attaches the event:
However surrounding the whole loop may prevent future bugs arising 🙂