Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which child was clicked from parents onclick event

I have a table that contains many img elements. The table registers for the onclick event & when it receives the onclick event I want to determine which img was clicked(if any).

I know I could just place a onclick event in each img element then I'd know if they were clicked but it also involves writing alot of long lines that pass the same information(repeating code -see below for what I mean).

So is there a way to look at the event object passed in the onclick event to determine which img element was clicked? If not maybe theres a way to do a hittest/collision test? Or maybe you know of another way?

<table onclick="openslideshow( event, new Array("img1.png","img2.png","img3.png"), "Author SlideShow");">
    <tr>
        <td><img class="screenshot" src="img1.png"/></td>
        <td><img class="screenshot" src="img2.png"/></td>
        <td><img class="screenshot" src="img3.png"/></td>
    </tr>
</table>

If I place an onclick event on each img it uses ALOT of repeating code:

<table>
    <tr>
        <td><img onclick="openslideshow( this, new Array("img1.png","img2.png","img3.png"), "Author SlideShow");" class="screenshot" src="img1.png"/></td>
        <td><img onclick="openslideshow( this, new Array("img1.png","img2.png","img3.png"), "Author SlideShow");" class="screenshot" src="img2.png"/></td>
        <td><img onclick="openslideshow( this, new Array("img1.png","img2.png","img3.png"), "Author SlideShow");" class="screenshot" src="img3.png"/></td>
    </tr>
</table>

Heres my function to attempt to determine which img element was clicked(when the table triggers the onclick event):

function openslideshow(evt, slideShowSrcs, dialogTitle)
{
    var selImg = evt.relatedTarget; // will this give me the clicked img & NOT the table?
    ... my code to open a JQuery dialog & show all slideShotSrcs in a sliding treadmill
}
like image 295
sazr Avatar asked Feb 22 '23 11:02

sazr


1 Answers

You are using jQuery so you can use the baked-in event delegation functionality:

$('table').on('click', 'img', function () {
    //now `this` refers the the image being clicked
});

Here is a demo: http://jsfiddle.net/LMzeB/1/

Note that .on() is new in jQuery 1.7 and for versions between 1.4.2 and 1.7 you can use `.delegate():

$('table').delegate('img', 'click', function () {
    //now `this` refers the the image being clicked
});

Here is a demo: http://jsfiddle.net/LMzeB/2/

You can also use the event object supplied to event handlers:

$('table').on('click', function (event) {
    //event.target is the initial target of the element
});

Here is a demo: http://jsfiddle.net/LMzeB/

like image 170
Jasper Avatar answered Feb 24 '23 00:02

Jasper