Andy Groom Andy Groom - 5 months ago 7
Javascript Question

Make exception of particular rows

I'm using this jQuery code to cause table rows to highlight when I hover over them:

$('#link-table tr').hover(function ()
{
$(this).toggleClass('highlight');
});


Is there anything I can alter on certain table rows to prevent them from highlighting when I hover over them?

Answer

You can simply add an if-condition in your hover handler to prevent this behavior.
For example, this code will only hightlight rows not having text Header:

$('#link-table tr').hover(function ()
{
    if (this.innerText !== 'Header')
        $(this).toggleClass('highlight');
});

However, JavaScript for intercepting hover is not justified for simple cases, when it is possible to do this using CSS.
You can simply use CSS :hover pseudo-class. If you want to enable this feature only for specified rows, then you can create your custom class:

tr.hoverable:hover {
  background-color: grey;
}
<table>
  <tr class="hoverable"><td>1</td></tr>
  <tr class="hoverable"><td>2</td></tr>
  <tr class="hoverable"><td>3</td></tr>
  <tr><td>4 (not hoverable)</td></tr>
  <tr class="hoverable"><td>5</td></tr>
  <tr class="hoverable"><td>6</td></tr>
</table>

The opposite option is to create a class which will disable the feature, while it will be enabled by default - it is up to you:

tr:not(.not-hoverable):hover {
  background-color: grey;
}
<table>
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
  <tr><td>3</td></tr>
  <tr class="not-hoverable"><td>4 (not hoverable)</td></tr>
  <tr><td>5</td></tr>
  <tr><td>6</td></tr>
</table>