Adding mouse events to table rows using jQuery

In my example I will only be modifying the row’s css classes. The behavior would be very similar to what you may already be familiar with in phpMyAdmin’s interface.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
 $('tr').hover(function() {
  $(this).toggleClass('highlight');
 });
 $('tr').click(function() {
  $(this).toggleClass('selected');
 });
 $('tr:even').addClass('odd');
 $('tr:odd').addClass('even');
});
</script>

Everything should be pretty easy to understand except for the last 2 addClass commands. jQuery’s “:odd” and “:even” selectors behave differently than you may expect. You could assume the “odd” selector to start at the “first” row but that is not the case (an array’s first element zero-index unless otherwise defined). Unless I included a heading row, my “first” row is actually an even row since it is referenced as an array and has an index of zero. That’s why it looks like I am doing it backwards 😉

One thought on “Adding mouse events to table rows using jQuery

Leave a Reply to DaxServer Cancel reply

Your email address will not be published. Required fields are marked *