views:

139

answers:

2

Hello,

There are two img elements that use the same map with one area. Now, we bind e.g. a click event handler to the area element. Is it possible to determine from the event handler which image instance has been clicked?

A: 

A possible solution is to use its offsetParent property. This way, I get the parent, which is what I originally needed. Finding the image itself also shouldn't be too difficult, provided that the images are contained in different divs.

David Parunakian
A: 

Yes, you can determine which image was clicked on by either:

  1. attaching a single event handler on a parent element and inspecting the event.target property
  2. attaching individual event handlers on each image element.

For example, if your HTML looks like:

<div id="container">
    <img id="myimage1" usemap="theMap" />
    <img id="myimage2" usemap="theMap" />
    <map name="theMap">
    ...
    </map>
</div>

then the possible solutions are:

1)

document.getElementById('container').onclick = function(evt) {
    var target = evt.target || window.event.srcElement;

    switch(target.id) {

        case 'myimage1':
            alert('you clicked on myimage1');
            break;

        case 'myimage2':
            alert('you clicked on myimage2');
            break;

        default:
            // click handler got some other evet
    }
}

2)

document.getElementById('myimage1').onclick = function() {
    alert('you clicked on myimage1');
}
document.getElementById('myimage2').onclick = function() {
    alert('you clicked on myimage2');
}

Depending on what you want to do after you capture the event, you'll have to return either 'true' to allow the URL to follow through, or 'false' to take an alternate action.

johnvey