I am using JQuery Templates to render a number of tables from a JSON data source.
Once the tables are rendered, I am attaching a Jquery “hover” event handler (via table CSS class) to highlight table columns.
The hover event works, but affects all rendered tables of the same CSS class – so If I hover over column 2 of table 1, column 2 of ALL my tables are also highlighted.
I would much prefer not to attach an individual ID for each table – nothing else would need it.
I have done some Googling and the use of JQuery “closest()” in the hover event handler seems promising, but I cannot figure out the correct usage 🙁
Any help would be very much appreciated.
$(document).ready(function() {
drawRows();
setColumnHover();
});
function drawRows() {
var jsonData = jQuery.parseJSON(getJsonString());
$("#tableTemplate").tmpl(jsonData).appendTo("#funnelBody");
}
function setColumnHover() {
/* Ref: http://www.local-guru.net/blog/2010/10/29/table-column-highlighting-with-jquery */
$(".statsTable td").hover(
function() {
var idx = $(this).parent().children('td,th').index($(this)) + 1;
if (idx > 1) {
$('td:nth-child(' + idx + ')').addClass('hover');
$('th:nth-child(' + idx + ')').addClass('hover');
}
}
,
function() {
var idx = $(this).parent().children('td,th').index($(this)) + 1;
if (idx > 1) {
$('td:nth-child(' + idx + ')').removeClass('hover');
$('th:nth-child(' + idx + ')').removeClass('hover');
}
}
);
}
///////////// Rendered HTML
<table class="statsTable">
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
Just need to focus on assigning the class by “this” instead of by name. The following should do the trick.