Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set an event on the specific point of an image?

I have a image like this:

enter image description here

All I'm trying to do is print a message in console like these:

console.log("#1 point is hovered");
console.log("#2 point is hovered");

See? I want to detect mouse hover on every point on the image. Is doing such a thing possible?

like image 682
stack Avatar asked Mar 07 '23 17:03

stack


1 Answers

There are <map> and <area> tags in HTML:

<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">

<map id="imagemap" name="planetmap">
  <area shape="circle" coords="104,101,15" href="first.htm" alt="First Point">
  <area shape="circle" coords="331,243,15" href="second.htm" alt="Second Point">
</map>

https://www.w3schools.com/tags/tag_map.asp

So you can attach an event to any defined area (circle, polygon or rectangle) and manipulate it with javascript. See example below:

var points = document.querySelectorAll('#imagemap area');
result = document.getElementById('result');

Array.prototype.slice.call(points).forEach(function(point) {

  point.addEventListener('mouseenter', function() {
    result.innerHTML = this.alt + '<br>' + result.innerHTML;
  });

});
#result {
  background-color: #eee;
  padding: 10px 15px;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  max-height: 50px;
  overflow: auto;
}
<img src="https://i.stack.imgur.com/Uy5nT.jpg" width="454" height="340" alt="Planets" usemap="#planetmap">

<map id="imagemap" name="planetmap">
  <area shape="circle" coords="104,101,15" href="first.htm" alt="First Point">
  <area shape="circle" coords="331,243,15" href="second.htm" alt="Second Point">
</map>

<div id="result"></div>
like image 54
Sergey Sklyar Avatar answered Mar 10 '23 10:03

Sergey Sklyar