views:

153

answers:

5

I want to trigger an event handler when the user hovers on a particular part of the image, like the center of the image or the right side of the image (area would include, say, about a 100 pixels). I am not using any framework, so this is normal javascript that I am working with. I am not sure if using image maps would work. Can anyone help?

A: 

You can use the MouseMove event to find out the location of the cursor, and then implement your own logic to calculate this position relative to the image.

See this page on getting the mouse coordinates.

Assaf Lavie
+1  A: 

Quirksmode about mouse position

Given the craziness involved here I would:

  1. Use a framework (I just did something like this with Mootools)
  2. Put absolutely positioned divs over the image and listen to events on them, instead of the image (did this too recently, a left 50% and a right 50%, way less cumbersome than tracking the mouse position).

Or go for it, quirksmode gives a decent function to get the mouse position, then you'll need to calculate the position of the image, then do the math to get the position of the mouse on the image, do the math in a mouseover event of the image, then continually check if the position meets your criteria, then do something about it when it does :)

rpflo
A: 

i do not know how many areas you need and if they need to be especially shaped or something like that....

a straightforward solution would be placing (CSS) empty div elements "over" the image which will trigger the events

afaik it is not possible to trigger js events with an image map

peter p
A: 

I suggest putting an invisible div in the place where you want to check for mouse_over in the image. (In the case that the area you want is rectangular of course). And then trigger on mouse_over for this div.

If you want to check for non rectangular areas (that can't be a div), I would suggest that you put a div of the same size of the image on top of it. Check mouse position on that div, and use it to compare with a mask image.

Example:

MousePosOnGhostDiv_X = 76;
MousePosOnGhostDiv_Y = 145;

if(CheckColorOfMaskImage(MousePosOnGhostDiv_X,MousePosOnGhostDiv_Y)=="orange") do something.

By knowing which color it is on the mask image you can set multiple events.

fmsf
A: 

An image map coupled with jquery is a great solution I've used before. I see that you're not using a framework, but it's worth a look.

Here's a little code snippet I used with an image map and mouseenter / mouseleave events.

$(".map-areas area")
.mouseenter(function() {
    idx = $(".map-areas area").index(this);
    showMapArea(idx);
})
.mouseleave(function() {
    $(".map-hovers img").hide();
    $(".map-titles img").hide();
});
ScottE