JQuery hover, image map, loops and arrays

I want to use the jQuery guidance method to roll over an image map of a base area that includes many odd shapes, so rolling each exact shape triggers an image exchange, as well as an .innerhtml exchange in a separate text block. I started by saying that the β€œnull” placeholder image is completely transparent, then change to png above the display area of ​​the live image when you roll over, and then go back to the zero image when you deploy.

So, the code for a zone with one zone looks something like this: Here isamapImage1 corresponds to the 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 if I declare each hover function explicitly. For 20 images that generate a ton of unnecessary code; obviously he is screaming about arrays and loop. So ... it should just be populating two arrays: one for image map areas and one for swap images. Writing to the console after the loop gives me what I expect, but the freeze function does not work. Since Ive never done anything in JS, I strongly suspect that there is a brain operator error caused by JS / jQuery syntax or scope. As far as I can tell, the variables should be available for the hover function (?). Both arrays return strings. jQuery has syntax that puts selectors in single quotes; when I tried setting up the imageArea array to include quotes explicitly,the hang caused a very strange syntax error, so I assume jQuery uses regular strings instead.

!

$(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');
    });

};

});
+3
1

, for, = 21.

EDIT: : "jQuery". , .

:

$(document).ready(function() {
  for(var i = 1; i < 21; i++) {
    $('#areamap_Image' + i).data('rolloverImage', 'images/image' + i + '.png');
  }

  // Replace 'area' with a more specific selector if necessary
  $('area').hover(
    function() {
      $('#imageSwap').attr('src', $(this).data('rolloverImage'));
    },
    function() {
      $('#imageSwap').attr('src', 'images/image0.png');
    }
  );
});
+3

Source: https://habr.com/ru/post/1706639/


All Articles