Higlighting Table row in JQuery
15 January, 2010 Leave a comment
Recently when refactoring the JQuery old code, about a year ago and i found an old and un-JQuery solution where using inline Javascript in HTML. Inline Javascript are bad which are the curse of HTML.
For example :
<table> <tbody> <tr onclick="rowClick('carID') onmouseover=rowOver('carID') > <td>whatever here </td> </tr> </tbody> </table>
1. Above inline Javascript will not be cache. Every time when the user refresh the page, it have to be reloaded again.
2. Hard to maintain and read something. You have to write everything in 1 line if the line is too long else you will get an error message like this “unterminated string literal” due to line break.
3.It is bad for javascript handling because it wont be able to access event object and
by reading you cant decide what this references to
One of the way to improve the code using jquery and using html class attribute.
<table> <tbody> <tr class="carDetails"> <td>whatever here </td> </tr> </tbody> </table>
Since the mouse over event are tie to “this” object, we can get or do anything that are wraped around this object.
$(document).ready(function() { $('tr.carDetails').mouseover(function(e) { $(this).closest('tr').addClass('highlightSelectedRow'); }); });
To get the selected row index you can follow the example. Using JQuery closest is one of the way :
//this will return the row index var rowIndex = $(this).closest('tr').parent()[0].sectionRowIndex;
or
//this will return the row index as well var rowIndex = $(this).closest('tr').removeClass('highlightSelectedRow').prevAll().length;
In the above example, when the user move the mouse over the table row, the tr will be added with css class ‘highlightSelectedRow’ to highlight the row color. You can see that we are using JQuery traversing/closest which are available in JQuery 1.3. The new version of JQuery 1.4, allowed array to be passed in. What it does are it get a set of elements containing the closest ancestor element that matches the specified selector, the starting element included.
New example :
<div id="a"> <div id="b"><b class="carName">ABC</b> <div id="c"><b class="carName">CDE</b> <div id="d"><b class="carName">DEF</b> </div>
$(document).ready(function() { $(".carName").mouseover(function() { //return id of div b or c or d which depends on the text that the mouse event is trigger. var id = $(this).closest("div").attr("id"); }); });
Quote from JQuery website :
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn’t match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.