Search code examples
javascriptimagemap

Dynamically create Image map via javascript


UPDATE I've compare objects in the debugger and it seems the map element is not a child of the img. However removing img.appendChild(map); still didn't get it to work. To be complete - along with the accepted answer, I had to add div.appendChild(map); so that the map has a parent.

I am trying to dynamically create an image area map. I have a jsFiddle of the code below: Here. I have successfully been able to generate a static map and bind a mouseover on the area via js, but I can't seem to create the map from scratch. I am using pure js. Any help would be appreciated.

<head>
<script>
    function function1() {  
    var img = document.getElementById("myImg");
    var map = document.createElement("map");
    map.name = "myMap";

    var area = document.createElement("area");
    area.shape = "rect";
    area.coords = "0,0,100,50"
    area.onmouseover = function(){alert("over")};

    map.appendChild(area);

    var div = document.getElementById("div");
    div.appendChild(map);

    img.usemap = "#myMap";
    }    


</script>
</head>
<body>
    <div id="div">
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150"
         id="myImg" 
         alt="Image" 
         width="350" 
         height="150"> 
    <br>
    <input type="button" value="Make area active" onClick="function1();">
    </div>

</body>

Solution

  • You need to use setAttribute instead of dot notation for setting the usemap attribute. That is, change the last line to this:

    img.setAttribute('usemap', "#myMap");
    

    I'm not sure why this is necessary, perhaps someone can add clarification as to why this standard attribute cannot be set using dot notation and requires setAttribute.

    See also this question, in particular the second answer: When to use setAttribute vs .attribute= in JavaScript?

    P.S. If your application uses a lot of DOM manipulation, then I'd recommend using a DOM library such as jQuery or Zepto; they will resolve issues like this for you and also any browser compatibility issues.