Getting linked img from HTML area

There are two img elements that use the same map with the same area. Now we link, for example. handler for the click event on the area element . Is it possible to determine from the event handler which image instance was clicked on?

0


source to share


2 answers


Yes, you can determine which image was clicked on:

  • binding one event handler per parent element and checking the event.target property
  • binding separate event handlers on each image element.

For example, if your HTML looks like this:

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

      

then possible solutions:



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 capturing the event, you need to return either "true" to resolve the URL or "false" to perform an alternate action.

0


source


A possible solution is to use the offsetParent property . Thus, I get a parent, and that's exactly what I needed. Finding the image itself shouldn't be too hard either, provided the images are contained in different divs .



0


source







All Articles