Click event listener on a <tr>
Question by Jonny Sooter
I have this event that listens for a click on a img then it switches the img for another, but this img can get real small and I wanted to make the entire tr click able. Any suggestions?
$('#example tbody td img').live('click', function () {
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
this.src = "images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
this.src = "images/details_close.png";
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
} );
Update
I tried using this but now my img won’t change. How would I select the img to use (this) or do I just make a var for it?
$('#example tbody td').on('click', function (e) {
var myImage = $(this).find("img");
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
myImage.src = "images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
myImage.src = "images/details_close.png";
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
} );
Answer by Mohammed ElSayed
first: it’s now better to use delegate() or on() instead of live(), which is now deprecated by the way.
second: just add a handler for the td, and by nature, it will get the same click event that will occur on your img, then you can eaisly select the img and play with it like nomral, consider the following example which is using the better way of on()
Update: I’ve modified the code a little bit to make it better
$('#example tbody').on('click', 'td', function (e) {
var myImage = $(this).find("img");
var nTr = this.closest('tr');
if ( oTable.fnIsOpen(nTr) )
{
/* This row is already open - close it */
myImage.src = "images/details_open.png";
oTable.fnClose( nTr );
}
else
{
/* Open this row */
myImage.src = "images/details_close.png";
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
}
you should now be ok with this solution, let me know if you need further help.
Answer by Starx
Pretty Simple
Select td instead of img
$('#example tbody td').on('click', function () {
P.S: Of course the live function has been deprecated so its better to use .on()