Striping a table with jQuery

jQuery makes striping an HTML table very simple with what amounts to a one line function.  First, let’s start with our HTML:

<table class="striped">

Should be pretty straightforward.  Notice that we haven’t done anything bayond a simple table here, no styling, nothing.  Next, we can create a simple CSS style for our alternating rows:

tr.alt {
background-color: #ebe9dc;

Finally, let’s create a Javascript function that we can call to stripe the table:

jQuery.fn.stripe = function() {
return this.each(function(){
$('tbody > tr:even', this).addClass('alt');

Again, this function primarily boils down to one line, the rest is boilerplate jQuery plugin code that allows us to make calls to the function as follows $('table.striped').stripe.

The power here is the line $('tbody > tr:even', this).addClass('alt');. Here, we are using selectors mixed with the scope of “this” (i.e. table’s with class “striped”) to select the even rows in the table and apply the class “alt” which we defined earlier in our style sheet to them.


jQuery: Focus on First Form Element

All in all, jQuery is pretty cool. I just stated working with it for a personal project and have found it simple and fairly intuitive to use, not to mention the plethora of available plug-ins.

I wanted to focus on the first input element in a form using jQuery. I haven’t tested this extensively, but I came up with the following:

    $(document).ready(function() {
       // focus on the first text input field in the first field on the page
        $("input[type='text']:first", document.forms[0]).focus();

We are simply using a selector to pick the first input element of type “text” in the first form on the page (that’s the “document.forms[0]” stuff) and then focus on it. Of course, this is limited only to text fields, but could be extended to other types as well. I’d be interested in hearing about alternatives.