Home » Tutorials Beginner Tutorial

Easy Table Reading in JavaScript, Page 2

2.2/5.0 (25 votes total)
Rate:

Jonathan Fenocchi
February 17, 2006


Jonathan Fenocchi
Jonathan Fenocchi is a talented young developer coming at you from southern TX, USA. Accessibility advocate, proficient programmer, and determined designer, Jonathan spends his free time researching new technologies, developing new ideas, playing video games and listening to rock music. Jonathan runs a Slightly Remarkable blog where he focuses on web-related content, and continues to pursue his goals as an aspiring web developer."

Jonathan Fenocchi has written 20 tutorials for JavaScriptSearch.
View all tutorials by Jonathan Fenocchi...

We begin with the variable “elem.” This global variable is the element of the table that we want to alter, specifically, the table row. You can change its value to “TD” to affect each cell of the table individually (although the alternation pattern for the background of each tends to get a little mixed up at that point, because they don’t line up horizontally as they would in a table row). Next, we call the “onload” event handler to run a function. In other words, we’re telling JavaScript “run this code when the document loads.” This way, we can put our code in the HEAD tags – or even in an external JavaScript file – and the table rows will be affected after the document loads. Since the document will always finish loading before the code is executed, no tables will be “left behind” or “forgotten.” The first thing that happens after the document loads is an if statement. If “document.getElementsByTagName” returns a null value, it means that the browser is too old to understand our code. To avoid unnecessary errors, no code will be executed for browsers that don’t understand the “getElementsByTagName” method.

Now that we know we can use the “getElementsByTagName” method, we can run the part of the code that actually does what we want, create alternate colors. We begin by setting the variable “el” to equal the group of elements that “elem” refers to. In other words, “el” becomes an array of all the “TR” elements. After that, we use a for loop to iterate through all the table rows.

Since we don’t want to affect the table headings (TH tags), or tables that do not have the “tbl” class name, we run another if statement in our for loop. This ensures that (1) the cells inside the current row are not table headings, and (2) the table does in fact have the “tbl” class name. Also, notice how the indexOf method was used rather than the “==” operator; this is because a table can have multiple classes, delimited by a whitespace. For example, you could add the class “firstTable” to any specific table you want, and also include the second class “tbl” like so, <table class=”tbl firstTable”>. The table now has two classes, “tbl” and “firstTable.” This means that you can format different tables with the same JavaScript.

Once we’re sure that the current row is acceptable to affect, we run yet another if statement – an extremely important one. We divide the value of “i” (which represents the nth row that we are currently on) by two and get its remainder. The remainder will always yield one of two numbers: 0 or 1. This way, we will tell if “i” is odd or even. In the event that it is odd (1), we update the class name of the current row to equal “on.” If it is even (0), however, we update the current row to have a class name of “off.” This way, each row’s styling information will alternate from one class to another.

Adding Complexity

You’ve just learned how to alternate styles on table rows with JavaScript. That’s great, but there’s so much more that you can do. In the opening of this article, I mentioned alternating abilities and one other thing – event handlers. There is more alternation code to be written, but this time in direct relation to an event.

What is an event-handler? The dictionary briefly defines the word “event” as “an occurrence.” A handler, as suggested by the name, “handles.” Putting the definitions together, an event-handler is basically “the code that is triggered when the user does something.” A few examples are: onclick, ondoubleclick, onmouseover, onmouseout.

So how can we use event-handlers to our advantage? We want to apply a “mouse over” event to every table cell, causing a highlight effect on whichever row we point to. Here’s our new code:

  <script type="text/javascript"><!--
    var elem = "TR";

window.onload = function(){
  if(document.getElementsByTagName){
    var el = document.getElementsByTagName(elem);
      for(var i=0; i<el.length; i++){
        if(el[i].childNodes[0].tagName != "TH"
        && el[i].parentNode.parentNode.className.indexOf("tbl") != -1){
     if(i%2 == 1){
        el[i].className = "on";
       el[i].onmouseout = function(){
                this.className = "on";
       }
    } else {
       el[i].className = "off";
       el[i].onmouseout = function(){
                this.className = "off";
       }
    }
       el[i].onmouseover = function(){
                this.className = "hover";
       }
      }
     }
  }
}
   //--></script>

See the following example.

Earlier, I mentioned the “onmouseover” and “onmouseout” event-handlers; here we see them in action. When writing JavaScript, you can set a property to a function, as in “onmouseout = function(){ … }.” In the same way, you can set a variable to a function. The most common way to do this is to use:

function myFunction(params) {
  // … code
}

“myFunction” is simply a variable that contains executable code and an object data type. We could write the same code as above like this:

var myFunction = function(){
  // … code
}

Since the “onmouseout” attribute is an event-handler and is triggered at a specific time (when the user moves his mouse out of focus of the object), the function we write will also be triggered at that time. This means that we can write many lines of code to trigger “onmouseout” and attach that code to a specific element without ever having to set the “onmouseout” attribute!

Here, the onMouseOut function says: “When the user moves their mouse off of this specific element, set its class to what it was before.” This applies to both “on” and “off” rows – they just have different classes, so they deserve different code in their onMouseOut events.

Next. We set the onMouseOver function for all of the rows, no matter whether they are “on” rows or “off” rows. We just want to highlight them when the mouse moves over them.

There’s More to It!

There is more, and it just keeps getting better! Let’s add another step of functionality: clicking. JavaScript is more powerful than just alternating styles on different rows and altering styles on highlighted rows – we need to be able to select and deselect a row. Take the following code:

  <script type="text/javascript"><!--
    var elem = "TR";
    var rClick;

window.onload = function(){
  if(document.getElementsByTagName){
    var el = document.getElementsByTagName(elem);
      for(var i=0; i<el.length; i++){
        if(el[i].childNodes[0].tagName != "TH"
        && el[i].parentNode.parentNode.className.indexOf("tbl") != -1){
        if(i%2 == 1){
          el[i].className = "on";
          el[i].oldClassName = "on";
          el[i].onmouseout = function(){
                this.className = "on";
         }
       } else {
         el[i].className = "off";
         el[i].oldClassName = "off";
         el[i].onmouseout = function(){
                this.className = "off";
         }
      }
         el[i].onmouseover = function(){
             if(this.className == this.oldClassName)
                {this.className = "hover";}
         }
         el[i].onclick = function(){
           if(rClick){
             rClick.className=rClick.oldClassName;
             rClick.onmouseout = function(){this.className = this.oldClassName};
         }
           this.className = "click";
           rClick = this;
           this.onmouseout = function(){return true};
         }
       }
     }
   }
}
   //--></script>

See the following example.

First, you'll notice the "rClick" variable - this variable is used to store an object. Next, we'll use the "oldClassName" property to store data (in specific, a class name). There is no "oldClassName" attribute, but we're creating one to store information. In this case, we're using it as a variable attached to a specific object, whereas the "rClick" variable is just a variable that will become an object of its own. We've also changed our onMouseOver function a little. Instead of always changing the class to the "hover" state (where it is highlighted), we make sure that the element we are highlighting has the original class it was assigned. In other words, since the "oldClassName" and the actual "className" of the element are set to be the same by default, every row will be highlighted onMouseOver. Additionally, we added an "onClick" event later on in the code that will affect the row. We don't want the row to attain the "hover" state when we click it or move our mouse off of the selected row, so we make sure that its old and current values are equal.

--Next page--


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow