Search code examples
javascriptcssdom-eventsarea

How do you JavaScript style area elements on mouseover?


I've got an image map with 20 area elements, only four shown below. I want to style each area so that a blue border appears whenever a user hovers over it - all the area shapes are rectangles.

<map id="mymap" name="mymap">
    <area shape="rect" coords="0,0,223,221" href="http://..." />
    <area shape="rect" coords="226,0,448,221" href="http://..." />
    <area shape="rect" coords="451,0,673,223" href="http://..." />
    <area shape="rect" coords="677,0,1122,223" href="http://..." />
    ...
</map>

I've tried using CSS to style each area, but it's not working. And I've tried to put an onmouseover=color() on the map element and call the following function, but that doesn't seem to be working either:

function color() {
    var blueboxes = document.getElementsByTagName('area');
    for(var i=0; i<blueboxes.length; i++) {
        blueboxes[i].style.border = 'solid blue 5px';
    }
}

Solution

  • mapper.js can be used for this.

    Mapper.js 2.4 allows you to add automatic area highlighting to image maps on your webpages (inc. export to SVG). It works in all the major browsers - Mozilla Firefox 1.5+, Opera 9+, Safari and IE6+. On older browsers, it can use "jsgraphics" from Walter Zorn (if installed), else it'll degrade and your visitors won't notice a thing.

    Sample code from that website:

    Please note that everything below this line is his code and wording, not mine. Full attribution belongs to the link above.

    Setting Up

    Download mapper.js and include it into your webpage.

    <script type="text/javascript" src="wz_jsgraphics.js"></script>
    <script type="text/javascript" src="mapper.js"></script>
    

    "wz_jsgraphics.js" is copyright by Walter Zorn and not part of the distribution!

    Using It

    To get the highlighting just add a class="mapper" to an div surrounded image.

    <div>
    <img src="..." class="mapper" usemap="..." alt="...">
    </div>
    

    To get individual area highlightings add one or more classes to the area.

    <map>
    ...
    <area shape="poly" class="noborder icolor00ff00" href="#" coords="...">
    ...
    </map>
    

    To get multiple area selections add one or more id's to the areas rel attribute.

    <map>
    ...
    <area shape="poly" id="blue" rel="green,red" href="#" coords="...">
    <area shape="poly" id="green" rel="red,blue" href="#" coords="...">
    <area shape="poly" id="red" rel="green,blue" href="#" coords="...">
    ...
    </map>
    

    To force a group of areas using the attributes of the initial area.

    <map>
    ...
    <area shape="rect" id="black" class="icolor000000 forcegroup" rel="green,red,blue" href="#" coords="...">
    ...
    </map>