I have multiple images on a page, all using the same image map. I need to know on what image the user clicked. Trouble is that $(this) returns a reference to <area>
instead of the <img>
. Here's the code:
<img src="image.png" usemap="#imageMap"/>
<img src="image.png" usemap="#imageMap"/>
<img src="image.png" usemap="#imageMap"/>
<map name="imageMap">
<area shape="rect" coords="0,0,27,12" href="javascript:;" onclick="up($(this));">
<area shape="rect" coords="0,13,27,25" href="javascript:;" onclick="down($(this));">
</map>
How do I know in the up
and down
functions which is the clicked image?
There is Only One Map
If you expect this to make multiple instances of area
for each img
, you're going to be disappointed. No matter how many img
you apply a map
to, it's still just the same one map
with the same 2 area
inside. So using $(this)
inside of the onclick
won't be much help.
What You Really Need
Is the index
of the current img
when an area
is clicked; which is easy to get.
jQuery
var n;//index of current image
$(document).ready(function() {//on ready
$('img').each(function(i) {//get index
$(this).hover(function() {//and on hover
n = i;//set index
});
});
});
Which now means that your onclick
can now be just up()
or down()
since using $(this)
does not return the current image.
Made a fiddle which highlights the current image so you can get a good idea of how it works.