Hightlight a table row on click using jQuery
February19
The scenario: Every time you click on a row, the row highlights. When you click on the highlighted row - remove the highlight.
The jQuery / Javascript code:
-
-
//highligths the clicked row
-
function highlightrow(obj) {
-
if ($(obj).attr("style")==‘background-color: rgb(255, 255, 187);’ || $(obj).attr("style")==‘BACKGROUND-COLOR: #ffffbb’) {
-
$(obj).removeAttr("style");
-
} else {
-
$(obj).attr("style","background-color: #FFFFBB;");
-
}
-
}
-
And for the HTML Code:
-
-
..rest of the HTML tags here…
-
< tr onclick="highlightrow(this);" >
-
..rest of the HTML tags here…
-
The reason for having this:
background-color: rgb(255, 255, 187);
and
BACKGROUND-COLOR: #ffffbb
is because Firefox returns: background-color: rgb(255, 255, 187); while IE returns something like this: BACKGROUND-COLOR: #ffffbb
Hey wenbert, try not using .attr(’style’) but rather use the built-in jQuery css functions!
Your code will mess up style, if you have other style definitions in the tag…
JS:
$(document).ready(function(){ $("tr").click(function() { $(this).toggleClass("active"); } });CSS:
.active { /*highlight class, add a background color, change the border or font color, whatever */ border: 1px dashed red; background-color: green; }HTML:
………
…