Given some click event for a table row:
$("tr.somerow").click(function(){
//do some stuff
//can I determine the TD under the cursor at the time of clicking?
})
Can I determine which TD (or any child elements) was under the cursor at the time of clicking?
Given some click event for a table row:
$("tr.somerow").click(function(){
//do some stuff
//can I determine the TD under the cursor at the time of clicking?
})
Can I determine which TD (or any child elements) was under the cursor at the time of clicking?
Share Improve this question edited Sep 6, 2011 at 14:20 Brad Mace 27.9k18 gold badges109 silver badges152 bronze badges asked Sep 6, 2011 at 13:56 Mutation PersonMutation Person 30.5k18 gold badges100 silver badges165 bronze badges 2- It would be easier to put the click event on the TDs and determine the TR from there instead. – RoToRa Commented Sep 6, 2011 at 13:58
- @RoToRa - I did think of that, but I wasn't sure about binding potentially hundreds of cells pared with dozens of rows. You've also got to contend with padding and whether or not the gaps between the cells will yield a click. – Mutation Person Commented Sep 6, 2011 at 14:03
3 Answers
Reset to default 5If you are able to change the script then do so to take advantage of jquerys .delegate function. This avoids having multiple bound click events and also in the event handler the this context will be that of the clicked td element.
$('tr.somerow').delegate('td', 'click', function(){
//this refers to the td
})
$("tr.somerow").click(function(e){
var target = $(e.target); // sets to the td or the element that was clicked
//do some stuff
})
To find the clicked <td>
regardless of any child elements, use var target = $(e.target).closest("td");
instead.
A couple mostly correct answers, but one misses the closest, and the other does a lot of unnecessary error handling.
$("tr.selector").click(function(e){
var td = $(e.target).closest('td');
});