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
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With