Image map: action onclick of area

When a user clicks on an image on my site, I want to cause an action only if they click within some specified area.
I have done this with some success with image maps and areas by specifying the href.
But specifying the href allows me to provide a link to a new page. Rather, I need some javascript to be executed when the area is clicked and in the javascript I need to know which image on the page was clicked.
Any suggestions?

Thanks,
Sam

If the href is to something like “#lebanon” then the link will not go to another page. You can also cancel the default action (following the link) like so:

var area = document.getElementsByTagName('area')[0];
area.onclick = function() {
  // do stuff
  return false; // returning false stops the link being followed
}

what would happen when I substitute the href url with something like “#lebanon”?
would a function called lebanon be called?

you provided the example below. area is the element with tag name area. But what element has the tag name area? the map? or the image? or the area?
I suspect you mean the area element, but what are the coordinates relative to if not referenced by the image element as a part of the map?

thanks,
Sam

var area = document.getElementsByTagName(‘area’)[0];
area.onclick = function() {
// do stuff
return false; // returning false stops the link being followed
}

The href attribute in HTML tells the browser where to go when a user clicks on that link, whether it’s a normal link or an area of an image map. “#lebanon” would point to an element on the page which has the ID “lebanon”:

<a href="#lebanon">Lebanon</a>

<p id="lebanon">
  Information about Lebanon
</p>

Clicking the link would make the browser scroll down to the paragraph.

But what element has the tag name area? I suspect you mean the area element, but what are the coordinates relative to if not referenced by the image element as a part of the map?

I suggest you go and look at the reference if you’re asking this sort of question.

The code I posted was just an example. You can access the area (the thing you click on) via document.getElementById or any other DOM method. But since you didn’t provide any HTML to look at, it’s hard to say what the best way is.