Monthly Archives: October 2008

Josh asks the CSS Guy about row locking with jQuery

With regards to this article, Josh writes:

“Would it be possible for you to recreate this with jQuery and see how many lines of JS you can save in the process?”

Yes!

This is a direct jQuery replacement of this particular example.

The jQuery

I ditched all the home-grown functions, linked out to the jQuery-latest.js, then wrote the following bits:

$(document).ready(function() {
  $('.pickme tbody tr:odd').addClass('odd');
  $('.pickme tbody tr').hover(
    function() { $(this).addClass('highlight'); },
    function() { $(this).removeClass('highlight'); }
  ).click( function() {
    $('.selected').removeClass('selected');
    $(this).addClass('selected').find('input').attr('checked','checked');
  });
});

In English, this says:

  1. When the page has finished loading the DOM…
  2. add a class of ‘odd’ to every other row in the table…
  3. then assign a hover behavior that consists of:
  4. adding a class of ‘highlight’ to the row when hovered into…
  5. and removing the class of ‘highlight’ when hovered away.
  6. When any row is clicked…
  7. remove the class of ‘selected’ from any other row that happens to have it…
  8. then add class of ‘selected’ to the current row, while also checking it’s radio button.

This is much shorter and easier to write for than the previous example. Compare the javascript written in the source code on the previous version to the jQuery version.

The usual warnings for using libraries still apply. If it’s a single effect on your site, it is likely best and more concise to write out your functions from scratch, but if you are already using jQuery (or any other library) on your site, take advantage of it. Also, just because it’s easy doesn’t make it right – give consideration to whether a behavior should be applied at all.