Heinzi
Heinzi

Reputation: 172310

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:

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?

Upvotes: 0

Views: 2953

Answers (1)

pashute
pashute

Reputation: 4063

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
  */
});

Upvotes: 1

Related Questions