Skip to content

Instantly share code, notes, and snippets.

@Ripley6811
Last active September 2, 2015 06:57
Show Gist options
  • Save Ripley6811/adf2201dc7fd373dc772 to your computer and use it in GitHub Desktop.
Save Ripley6811/adf2201dc7fd373dc772 to your computer and use it in GitHub Desktop.
How to highlight a HTML table row when it gets focus by clicking any sub-element.
...
<!-- KnockoutJS used to iterate over products list -->
<tbody data-bind="foreach: products">
<tr onclick="highlightRow(this)">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</tbody>
...
<script>
// Reference to active/clicked row
var active_row = null;
/**
* Highlight table row by changing background color of each cell.
* @param {Object} tr_el The HTML <tr> element to iterate over
*/
var highlightRow = function (tr_el) {
// Clear highlighting of previous row
for(var i = 0; active_row && i < active_row.children.length; i++) {
active_row.children[i].style.removeProperty("background-color");
}
// Change saved reference to active row
active_row = tr_el;
// Add highlighting to new row
for(var i = 0; i < active_row.children.length; i++) {
active_row.children[i].style.backgroundColor = 'yellow';
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment