2

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>
agrm
  • 3,735
  • 4
  • 26
  • 36

2 Answers2

7

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>
agrm
  • 3,735
  • 4
  • 26
  • 36
  • 1
    `` does not use or need a closing slash and never has. – Rob Jan 11 '18 at 19:59
  • I guess old habits die hard. You're right, thanks for notifying! Updated the answer. – agrm Jan 11 '18 at 20:06
  • A number of people keep saying that but the HTML spec never put a closing slash there so I don't know how one acquires such a habit. – Rob Jan 11 '18 at 20:15
  • 1
    I can only answer on my own behalf, but self closing tags were part of the XHTML spec from when I started coding for the web. I guess that's how – agrm Jan 11 '18 at 20:24
  • 1
    @Rob XHTML, which is closer to the XML specification than HTML is, requires closing standalone tags. Some people might be conflating the HTML and XHTML specifications with habits like that. – Patrick Roberts Jan 11 '18 at 20:27
-3

onclick="Popup('Hydrogen')" it is a function, I think you must put semi-colon ';' after the code. Like this onclick="Popup('Hydrogen');"

cosmoonot
  • 2,161
  • 3
  • 32
  • 38
admm
  • 1