
456 views
How to create an image map in JavaScript
To create an image map in JavaScript, you can use the HTML <map> and <area> elements along with JavaScript to handle the interactivity. Here’s a step-by-step guide on how to create an image map using JavaScript:
- Create an HTML
<img>tag with theusemapattribute to specify the map name. Set thesrcattribute to the image file path:
HTML
<img src="your-image.jpg" usemap="#yourMapName" alt="Your Image">- Below the
<img>tag, add a<map>element with a unique name matching theusemapattribute from the<img>tag:
HTML
<map name="yourMapName">
<!-- Define areas using <area> tags -->
</map>- Inside the
<map>element, define the clickable areas using<area>tags. Each<area>tag represents a specific region on the image. Set theshapeattribute to define the shape of the area (“rect” for rectangle, “circle” for circle, or “poly” for polygon), and set thecoordsattribute to specify the coordinates of the shape. Thehrefattribute represents the link destination for that area:
HTML
<map name="yourMapName">
<area shape="rect" coords="x1,y1,x2,y2" href="your-link-1.html" alt="Description 1">
<area shape="circle" coords="x,y,radius" href="your-link-2.html" alt="Description 2">
<area shape="poly" coords="x1,y1,x2,y2,x3,y3,..." href="your-link-3.html" alt="Description 3">
</map>Replace x1, y1, x2, y2, ... with the appropriate coordinates for each shape.
- Add an event listener to the
<map>element in JavaScript to handle the click events. Inside the event listener, you can perform actions based on the clicked area:
JavaScript
var map = document.querySelector('map[name="yourMapName"]');
map.addEventListener('click', function(event) {
// Perform actions based on the clicked area
var target = event.target;
var href = target.getAttribute('href');
// Do something with the href value, like redirecting to a new page
window.location.href = href;
});That’s it! You now have an image map in JavaScript. When a user clicks on one of the defined areas, the click event will be triggered, and you can handle it accordingly in the event listener function. Remember to replace "yourMapName" with the actual name you used for your map.