javascripthtmlimagemap

Executing javascript function with image map in HTML


I want to execute some a javascript function when i click on a certain part of the image in my cshtml page. However the clickable area does not appear.

I also dont want to reference www.google.com but it requires me to have alt and href attributes.

Why is my code not working?

Here is my code:

<image src="~/Content/Images/PeriodicTable2.jpg" width="900" height="450" alt="Sample Image" />

<map name="PeriodicTable">
   <area shape="rect" coords="0,0,200,200" onclick="Popup('Hydrogen')" href="https://www.google.com" alt="something"> 
</map>

Solution

  • You have to set the usemap attribute:

    <img src="..." usemap="#PeriodicTable">
    

    See the following example, where I added a dummy Popup() function to test:

    function Popup(text) {
      console.log(text)
    }
    <img src="https://via.placeholder.com/600x200" usemap="#PeriodicTable" width="600" height="200" alt="Sample Image">
    
    <map name="PeriodicTable">
      <area shape="rect" coords="0,0,200,200" onclick="Popup('Hydrogen')" href="#" alt="something"> 
    </map>

    As for the <area> and its attributes, HTML4 requires both the alt and href to be set (alternatively the nohref attribute).

    In HTML5, href is optional and alt is required only if href is used.

    As an <area> without a href is not considered a regular link, browsers will not show the mouse changing to a pointer when you hover the areas. This behavior can be changed using CSS: area { cursor: pointer }.

    This means the following example should work pretty much like the first one, but without the href and alt attributes.

    function Popup(text) {
      console.log(text)
    }
    area {
      cursor: pointer;
    }
    <img src="https://via.placeholder.com/600x200" usemap="#PeriodicTable" width="600" height="200" alt="Sample Image">
    
    <map name="PeriodicTable">
      <area shape="rect" coords="0,0,200,200" onclick="Popup('Hydrogen')"> 
    </map>