Thursday, August 14, 2008

Javascript image map

Have you ever needed to know exactly where the user has pointed or clicked on an image? Well, this is easily done with HTML image maps, they are quite useful. But they do have some disadvantages. Using an HTML/XHTML image map requires form submission or page redirection to be used. What if you need to display appropriate content somewhere on the page, depending on where the user has pointed? Here is a way to get the offset coordinates of the pointer, inside an image.

function get_image_offset(e, id)
{
offset_x = e.offsetX ? e.offsetX : e.pageX-document.getElementById(id).offsetLeft;
offset_y = e.offsetY ? e.offsetY : e.pageY-document.getElementById(id).offsetTop;
 
document.getElementById('x').innerHTML = offset_x;
document.getElementById('y').innerHTML = offset_y;
}

This function takes two parameters - the event (mouseover, click, mousemove), and the id of the element (image) that we wan't to use. It saves the offset in offset_x and offset_y. If client's browser is IE, the offsetX and offsetY values will be used, but since this is not supported by the other browsers, we can use the pageX and pageY values and the elements offsetLeft and offsetTop values to determine the cursor offset.

After the two lines of code have been executed we have the offset in the variables offset_x and offset_y and we can use them for any purpose. I have added two span elements to the HTML, which show the offset as the user moves the mouse over the image. Here is the rest of the code you need to get this working:

<img id='my_image_map' src='test.jpg' onmousemove='get_image_offset(event, this.id)'>
<br />
X: <span id='x'>0</span>; Y: <span id='y'>0</span>

Now, presuming you have a 'test.jpg' file inside the folder of your page, you will see that when you move the mouse over it, the values of the two spans change width the coordinates of the cursor offset. You can change the code that alters the innerHTML of the two spans and do whatever you need to do with this offset coordinates. You can also change the event that triggers the function. I use onmousemove to update the coordinates every time the cursor moves over the image, but you can use other triggers like onclick, ondblclick, etc.

P.S. You can see a demo of this code here and you can get the example code from here

No comments: