Creating Table Rulers with the jQuery JavaScript Library
Welcome to the final installment of a series on creating table rulers with CSS and JavaScript. Comprised of four approachable tutorials, this series demonstrates how to build a table ruler by means of several approaches, ranging from utilizing CSS and JavaScript separately, to using a balanced combination of them.
Creating Table Rulers with the jQuery JavaScript Library - Adding and removing CSS classes dynamically with jQuery (Page 3 of 4 )
As I said in the previous segment, my goal here is to build a table ruler with the assistance of the jQuery JavaScript library. If you’re not familiar with it, don't worry. I'm going to use only a couple of its methods for dynamically manipulating the CSS classes assigned to a selected web page element.
These methods are called “addClass()” and “removeClass()” respectively. I'm going to utilize them for highlighting the rows of a targeted HTML table, in this way creating the table ruler mechanism.
So, now that you’re well aware of the way that the table ruler is going to work, pay attention to the following JavaScript snippet, which uses jQuery to build it:
// example on building a table ruler with jQuery library
$(document).ready(function(){
// get all <tr> elements in selected table and build the ruler
$("#ruledtable tr").hover(
function(){
$(this).addClass("ruler");
},
function(){
$(this).removeClass("ruler");
}
);
});
</script>
Undeniably, the above code sample demonstrates in a nutshell the remarkable ability of jQuery to simplify the development of a JavaScript application. As shown before, the script first fetches all of the <tr> elements contained within the targeted HTML tables, and then uses the complementary “addClass()” and “removeClass()” methods to create the table ruler effect.
It’s hard to believe, but that’s all the JavaScript code required to highlight the rows of multiple tables. Of course, the above code sample is still incomplete; it dynamically assigns and removes a “ruler” CSS class from the <tr> elements of each selected table, implying that it’s necessary not only to show the definition of this class, but the structural markup that creates the tables in question.
Bearing in mind this requirement, in the last section of this article I’ll be building a new sample file which will include all the layers that compose this jQuery-based table ruler.
Please click on the link below and keep reading. We’re almost done!