ドキュメント

Tutorials:Zebra Striping Made Easy

From jQuery JavaScript Library

Jump to: navigation, search

Walking through the simple code needed to stripe table rows.

Original: http://15daysofjquery.com/table-striping-made-easy/5/
Author: Jack Born

Similar Tutorials: TraversingSelectorsCSSEvents

I've prepared a step by step demonstration to take someone else's well written JavaScript and reduce it down to 5 lines or less. At the same time you'll see how I make it a little more flexible and useful.

Take a look at "Stripe your tables the OO way" by Matthew Pennell. His code is clean and concise. And it's an improvement over a past article from A List Apart.

But with the help of jQuery, I think we can do better.

The concept is to create stripes on a table and then have the background of each row change color when your cursor rolls over.

Image:Zebra1.png

Contents

The Goal

As I mentioned, Mathew's code is quite good. It shows a level of skill that most part-time web geeks might find difficult to attain. It's certainly above the head of someone just starting to roll up their sleeves and learn JavaScript.

How can jQuery help?

My mission is to show you that jQuery can make this task:

  • Easier to accomplish
  • Faster to load on the page
  • More flexible to use

So what are you waiting for? Jump into the tutorial and see how easy jQuery makes table striping.

Starting Point

  • This demonstration is an adaptation of a well-written snippet of code by Mathew Pennell - "Striping Your Tables the OO Way"
  • Let's use Mathew's layout and style sheet as our starting point
  • No JavaScript yet
  • Here's how it looks:

Image:Zebra2.png

CSS To Pay Attention To

  • "alt" class will be applied to every other table row
  • This will give the zebra stripe
  • "over" class will later be used to create the highlight effect when the cursor moves over a row
  • I'm going to remove tr:hover from the style sheet because Internet Explorer doesn't support it
  • In "good" browsers (Firefox/Opera/etc) the tr:hover instruction works great - no JavaScript needed

Image:zebra3.png

One Minor Change

  • Add a class to the table we want striped
  • class="stripeMe"
  • Soon you will see that using the class (and not an id) gives us more flexibility
  • We will be able to pick and choose which table or tables on a page we want to stripe

Image:zebra2-b.png

First Steps With jQuery

  • First line grabs the jQuery library
  • Highlighted section is an improvement over the traditional window.onload function
  • Now our code will execute faster

Image:zebra4-b.png

The Basics - Made Simple

  • jQuery code starts with $
  • Followed by parenthesis
  • Inside parenthesis is what you tell jQuery to find - don't forget the quotes
    • $('p') = find all paragraphs
    • $('.whatever') = find everything with class="whatever"
    • $('.stripeMe tr') = find all tr (table rows) inside an element with the "stripeMe" class
    • In our example... find all rows of a table with class="stripeMe"

Image:zebra5.png

  • $('.stripeMe tr').addClass('alt'); means add the class "alt" to every row of any table with the stripeMe class
  • Note - We want to do alternating rows but let's tackle this one piece at a time

Alternating Rows Is Easy

  • $('.stripeMe tr').addClass('alt'); means add the class "alt" to every row of any table with the stripeMe class

Image:zebra6.png

  • This is not exactly what we want
  • The change is really easy
  • $('.stripeMe tr:even').addClass('alt');

Now our table is striped

Quick Recap

Image:zebra7.png

  • Just three lines of code gives us this:

Image:zebra7-b.png

  • Alternating rows!
  • Other examples on the web, no matter how well written, use lots of code - most of which is beyond the reach of the beginning coder
  • Now you can include these three lines of code (plus jQuery) and any table with class name "stripeMe" will be striped
  • Just one step left...

Highlight Row As Cursor Rolls Over

  • If you have used JavaScript before, you are familiar with onMouseover, onMouseout, onClick, onSubmit...
  • These are events. They can be used to trigger specific code to execute when the event occurs
  • jQuery makes events easier than you might imagine
    • Remember $('.whatever') means "Find elements with class name 'whatever'" (Simplified explanation)
    • $('.whatever').mouseover() tells jQuery "Everything with class name 'whatever' will have a new onMouseover event
    • Inside the mouseover parenthesis you will put a function. The function tells jQuery what happens when the event (mouseover) occurs

Image:zebra8.png

Add A Class When Mouseover Triggered

  • What you're about to see is as complicated as this tutorial gets. If you can make it past this... you're home free.
  • $(this) tells jQuery to refer back to the last time $() was called

Image:zebra9.png

  • Here's what this code means, section by section
    • Find all rows (tr) inside any page elements with class name "stripeMe"
    • Assign the mouseover event to each row
    • When the mouseover event is triggered, here is a function to execute
    • $(this) refers to all those rows jQuery found
    • Add the class "over" to those rows (on mouseover)

Mouseout

  • Mouseout is pretty much the same as before
  • Instead of addClass we use removeClass

Image:zebra10.png

The Finished Product

  • (The tutorial is not over... but let's see what we've accomplished)
  • We could quit here... but jQuery gives us the flexibility to shorten up our code even further
  • Here is our live example:

Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet
Lorem Ipsum Dolor Sit Amet

Did I Goof?

  • "What the heck, Jack... you said you were going to get this code down to less than 5 lines"
  • Here's where we are right now

Image:zebra11.png

  • Not bad... but let's do better

Chainable Methods

  • jQuery lets you 'chain' methods together
  • When you're giving jQuery two or more instructions for one element you can remove some redundancy
  • For example:
    • $('.whatever').mouseover().mouseout();
  • Here's what that looks like in the "wild"

Image:zebra12.png

  • $(".stripeMe tr").mouseover(function() {$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");});
  • Applying the instructions for mouseover and mouseout at the same time not only shortens your code... it makes sense
  • Now time for some "cheating"...

Pile It On One Line If You Want

  • If you've written it correctly, you should be able to write it on one line, like so:
 <script src="jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
   $(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
   $(".stripeMe tr:even").addClass("alt");
 });
 </script>
  • So, let's wrap up and see if using jQuery was worth it

Why Use jQuery?

  • jQuery helped us accomplish several key goals
    • jQuery slimmed down the code dramatically
    • We made use of the Document Object Model (advanced JavaScript) without climbing a steep learning curve
    • Our code allows us more flexibility since we can stripe any table on a page by giving it the "stripeMe" class name
    • Our code executes sooner thanks to jQuery since it doesn't wait for the entire page to load
    • We were able to chain several instructions together and save space and time

A limitation and a workaround

  • Use of table headers <th>, which are typically not striped the same as other rows, will not be formatted properly using this technique.
  • Another way to skip the header row is to extend the selector routine to avoid it. In the example above, $('.stripeMe tr:gt(0)').hover(..) will get all table rows except the first one.
  • It should be noted that there's a limitation with this particular solution. If you have more than one table, then the striping will start off on the wrong count for every other table.
  • Why does this occur?
    • tr:even Finds every-other table row in the entire document, it's not relative to a single table
  • How can we work around this?
    • jQuery has another selector tr:nth-child(even), this works just like tr:even, but it finds every even table row relative to the table itself.
  • Using this new selector, we'll always find the right-numbered table rows that we need.