Though they’re often treated like the redheaded stepchild of modern web design, tables are still one of the best ways of displaying concise tabular data. But the more data that gets packed into a table, the tougher they get to read. Zebra striping the rows helps some, and column striping can help even more.
One design technique I’ve always enjoyed is highlighting the row and column of any cell that the user hovers over. Highlighting a cell’s row is simple, because table cells are organized into rows: all you have to do is apply a style to tr:hover, and you’re done. Columns are harder because there’s no inherent structure for a column in a table, which means loads of complex JavaScript is inevitable. Or so I thought.
I’ve been building HTML tables for nearly two decades now. Today I realized two things:
- There’s such a thing as a col tag for tables (who knew?).
- It’s going to make my life easier.
The col tag is a special content-less element that lives inside of your tables. They’re used to specify columns in tables – columns that can be styled. The general use looks like this:
col 1 | col 2 | col 3 |
Unfortunately, since our table cells aren’t direct descendants of the col tag (like they are to the tr tag) and our columnss have no content, we can’t just use col:hover. However, having columns make the JS we have to write much, much simpler, particularly when using a library like jQuery. Check out this example:
See the Pen 45a262288e909448afed48374a9b8935 by Rob Glazebrook (@rglazebrook) on CodePen
I’m using a few nice jQuery tricks to make this as simple as it is. We’re using jQuery’s hover function, which fires both on mouseenter and mouseleave (this is important). When someone hovers (or un-hovers) over a cell, we first move up to the parent table. Then we find the col tag that has the same index as our td tag. (Indexes are zero-based, so the 3rd col in the table will have an index of 2… as will the 3rd cell in any row.)
Once we’ve found our column, we toggle a class of “hover” on it. ToggleClass is a nice shortcut function that adds a class if it’s not present and removes it if it’s already there. This is perfect for us, because jQuery’s hover function fires once when the cursor moves over our cell, and again when the cursor leaves the cell.
Once our JS is in place, the CSS becomes a piece of cake: just write styles for both tr:hover and col.hover. I’m using a semitransparent background color in the example above, so the cell we’re hovering over looks even darker.
And there you have it. Three lines of JS and two CSS rules later, we have an easier-to-read table.
One thing if you ever find yourself in a situation where you have to export an HTML table to CSV using JavaScript you should know it is quite simple and easy to do.