Search code examples
javascripthtmlimagemaparea

Get reference to image map area elements with JavaScript in IE8+


I'm trying to get references with JavaScript to area elements in an image map, but in IE8+ it's not working.

My HTML:

<div class="container">
    <img src="image.png" usemap="#hotspots">
    <map name="#hotspots">
        <area id="seg-1" href="" shape="poly" coords="167,286,113,379,320,379,266,286,167,286"/>
        <area... />
        <area... />
        <area... />
        ...
    </map>
</div>

My JavaScript:

document.getElementById("seg-1");

I assign a traditional event handler like this:

document.getElementById("seg-1").onmouseup = function() {alert("onmouseup called");};

This works in:

  • Safari 6 (OS X)
  • Chrome 26 (OS X)
  • Firefox 21 (OS X)
  • Chrome 27 (XP)
  • Chrome 27 (W7)
  • Chrome (W8).

But not in:

  • IE8 (XP)
  • IE9 (W7)
  • IE10 (W8)
  • Firefox 17 (XP)
  • Firefox 21 (W7)
  • Firefox 21 (W8).

When I run:

console.log(document.getElementById("seg-1"));

I get the element for the above browsers that work, but I get the URL of the page in the above browsers that don't work.

Any ideas how I can make this work?

PS: here's the jsFiddle: http://jsfiddle.net/Stimpski/Y5jeJ/


Solution

  • Despite of a nasty looking console.log(), document.getElementById("seg-1") refers to the HTML element, it's just area's toString() method showing an url.

    The reason why this is not working for some browsers is the name of the map. You should not use # in the name attribute of the map. # is needed only in usemap attribute of the img.