Wednesday, November 28, 2012

Multiple hyperlinks on an area (or image)

slicing + absolute positioning
I was working on a website which had a front banner that looked like a spice cup board and the owners wanted when you click on a certain "jar" it takes you to a certain page in the site. But they already had someone working on this before me and decided to use image slices + absolute positioning.

I'm not saying its a bad solution, I just don't like dealing with multiple images and other penalties (ie. maintenance) associated with it. I would rather go with a single large image and define regions in it that's clickable. That's where image maps come in.

Image maps enable me to define multiple links within a single image. It's clean and doesn't involve any JavaScript or CSS just plain HTML5 markup.

You start off by declaring the image:

<img scr="bigbanner.jpg" alt="frontpage banner" border=0 usemap="#hotspots"/>  

The new thing here is the usemap attribute. The value of the usemap attribute must be the same with the map id. The map element acts as a container for specifications regarding the map's active areas (ie. hotspots), where are define as area elements within the map.

 The matching map markup would be:

<map name="hotspots">  
      <area shape="rect" coords="20,20,170,170" href="somepage2.html"/>  
      <area shape="circle" coords="250,175,50" href="somepage3.html"/>  
      <area shape="poly" coords="117,241,277,312,84,370" href="somepage4.html"/>  

The shape of the area element is influenced by the *duh* shape attribute. Rectangles and circles are fairly easy to use but watch out for with poly. Its the most flexible and most tricky to use. In the example, I'm creating a "triangle"; the first 2 values in the coords form the first point, the second 2, form the second point and the third pair gives use the third (end) point. Given enough coords information, I can make the "poly" area follow the outline of any item on any image.

As for the coordinate values, I just have to remember that the top left corner of the image is 0,0. Also, map is a non-visual element so I can put it anywhere on the page markup.