Creating Interactive Client-Side Image Maps with HTML `<map>` and `<area>`
Learn how to build interactive image maps using HTML's `<map>` and `<area>` elements. This tutorial explains how to define clickable regions within images, link areas to URLs or JavaScript functions, and create engaging and dynamic user experiences.
Creating Client-Side Image Maps with the HTML `<map>` Element
Understanding Image Maps
An HTML image map allows you to define clickable areas within an image. This makes it easy to create interactive images where different parts of the image can trigger different actions, such as linking to different pages or running Javascript code. Instead of the entire image acting as a single link, you define specific regions within the image as clickable areas. This is achieved using the `<map>` element to define the clickable regions within the image, which is linked to the image using the `usemap` attribute of the `` tag.
Creating an Image Map
To create an image map, you need:
- An image (`<img>` tag) with the `usemap` attribute, linking it to the map.
- A `<map>` element that defines the clickable areas.
- One or more `<area>` elements within the `<map>` tag, each defining a clickable region.
The `<map>` element’s `name` attribute *must* match the value of the `usemap` attribute in the `` tag. This creates the link between the image and the clickable areas defined in the map.
The `<area>` Element: Defining Clickable Regions
The `<area>` element defines individual clickable areas within the image map. Key attributes include:
shape
: Defines the shape of the area (rect
,circle
,poly
, or `default` for the entire image).coords
: Specifies the area's coordinates (x, y values relative to the top-left corner of the image).href
: The URL or Javascript function to execute when the area is clicked.alt
: Alternative text for accessibility (required if `href` is present).
Example Image Map
<img src="image.jpg" usemap="#myMap" alt="My Image">
<map name="myMap">
<area shape="rect" coords="10,10,100,100" href="page1.html" alt="Area 1">
</map>
Browser Support for `<map>`
The `<map>` element is well-supported by modern browsers.
Browser | Support |
---|---|
Chrome | Yes |
Edge | Yes |
Firefox | Yes |
Opera | Yes |
Safari | Yes |
Default Styling and CSS Customization
Most browsers render the `<map>` element as an inline element by default. You can customize the appearance using CSS. Note that the map itself is not directly visible; styling affects only the linked image and the areas defined within the map.