Search code examples
jqueryhtmlcssimagemap

How do I make an imagemap area clickable with jQuery?


Minimal, complete example (jsfiddle):

<!DOCTYPE html>

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </head>
    <body>
        <map name="myMap" id="myMap">
            <area shape="rect" coords="10,10,100,100">
        </map>
        <img src="http://placehold.it/350x150" alt="" usemap="#myMap">

        <script type="text/javascript">
            $(function () {
                $("map#myMap area").click(function () {
                    alert("click!");
                });
            });
        </script>
    </body>
</html>

What different browsers do when hovering over the upper left-hand corner of the image:

  • Chome: Shows the "hand" cursor and reacts to clicks (this is the behavior I actually want).
  • Firefox: Does not show the "hand" cursor, but reacts to clicks.
  • IE and Edge: Neither show the "hand" cursor nor react to clicks.

I know that I can put href in the area tag, but it's a highly dynamic site and I'd like to do all sort of jQuery stuff with the area (hover highlight, click handler, etc.). I also know that I can fix Firefox's behavior with area { cursor: pointer; }, but that doesn't help with IE and Edge.

Do I have a bug somewhere in my code or is this a bug in IE/Edge?


Solution

  • You need the href. And you have to ignore events in the click function. Also, most readable if you give each area an id, or, if some areas respond in the same way, use a class (i.e. class="areaRed")

    e.g.

    <map name="myMap" id="myMap">
     <area id="area1" shape="rect" coords="10,10,100,100" href="#">
    </map>
    

    and in your click function

    $("#area1").on("click", function(e){
      e.preventDefault();
      /*
       your code here
      */
    });