Question

Is there a way to avoid repeating code when iterating over area elements with Jquery? or an easier way with plain javascript? A snippet of the HTML:

    <img id="img1" src="image.png" width="400px" height="400px" usemap="#area_click"title="click to shade different areas" />
<map name="area_click">
    <area href="" shape="poly" coords="33,149,53,151,49,183,45,205,27,197,29,171" alt="area1" >
    <area href="" shape="poly" coords="157,148,161,168,161,201,143,204,139,180,137,152" alt="area2" >
    <area href="" shape="poly" coords="51,144,55,126,57,114,41,88,32,112,32,140" alt="area3" >//...35 more areas follow...
</map>

I have tried...

  1. Create array from map children.

    var kids=$("map[name*='area_click']").children();
    
  2. Loop through the array.

    for (var k=0;k<kids.length;k++){
    kids[k].click(function(event){
        event.preventDefault();
        $("#" + AreaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);});}
    

I thought I was missing something about the array-like object created by children(). So I tried...

1.Create array from map children. Then use eq() to grab references to the DOM elements in the array.

    var kids=$("map[name*='area_click']").children();
    var kidsArray = kids.eq();

2.Loop through the array.

    for (var k=0;k<kidsArray.length;k++){
    kidsArray[k].click(function(event){
        event.preventDefault();
        $("#" + AreaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);});}

Also tried using $.each and find() instead of children(). But it seems $.each() cannot digest area elements. The following generates a type error in the jquery.min script in the Firebug console.

TypeError: t is undefined ...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"...

    var kids=$("map[name*='area_click']").find("area");
var k=0;
    $.each(kids.eq(k)).click(function(event){
        event.preventDefault();
        $("#" + areaArray[k]).fadeToggle(500).fadeTo(300,opacityArray[k]);
        k++;
    });

I'm sure I am doing something wrong in trying to pass a reference to the array to the for loop or $.each(), I just don't know what. Any help? Or am I going about the whole thing backwards?

Was it helpful?

Solution

Looks like a problem with the closure variable k, try

kids.each(function (k) {
    $(this).click(function (event) {
        event.preventDefault();
        $("#" + AreaArray[k]).fadeToggle(500).fadeTo(300, opacityArray[k]);
    });
})

Or

kids.click(function (event) {
    event.preventDefault();
    var k = kids.index(this)
    $("#" + AreaArray[k]).fadeToggle(500).fadeTo(300, opacityArray[k]);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top