Say we have an IMG
(id
less) element which has an usemap="#hotmap"
attribute. Then we have this <MAP name="hotmap">
element (in the BODY
) containing an enormous amount of AREA
s (say >1000). It's obvious, that we'd like to delegate the eventhandling of AREA
s to the MAP
element instead of creating hundreds of eventlisteners.
Now in the eventhandler function (for MAP
) we'd like to get a reference to the IMG
which uses the MAP
which fired the event. However, MAP
is in the BODY
and IMG
element can't have HTML, thus MAP
can't be among its children. So the question is, how can we catch the IMG
in this eventhandler?
A trivial example:
<img src="some_image.png" usemap="#hotmap" />
...
<map id="map" name="hotmap">
<area shape="circle" coords="100,100,50" />
...
</map>
map.addEventListener('click', function (e) {
var area = e.target,
image = ?; // How to refer the img
...
}, false);
Side notes
I'm working on a HTA project where I need an object which dynamically creates and assigns hotmaps for images which have certain custom attributes. This object gets its data for AREA
s from external file, and everything is working fine, except this one little detail. For now, I'm adding a custom property containing a reference to the "user" IMG
, to each AREA
. Though this would be unnecessary, if it could be done only once in the eventhandler.
EDIT
A live demo at jsFiddle, (not HTA included, works in any(?) modern browser)
EDIT II
I just realized, that I can't reuse the MAP
, since it can be also resized according to the IMG
. So I've put the reference to the IMG
to the MAP
instead of its AREA
s.
Though this solved my problem, I'd still like to know, how to get the IMG
in the eventhandler, just in general. The suggested querySelector()
solution seems not work (tumbled with it earlier, now it returns undefined
)