Display different color in alternate row using jquery
Posted on March 17, 2008
Filed Under javascript, jquery, tips and technique
Most of the tabular data are organized in such a manner that they are easy to read. And for this, most of the developers use different color to highlight the alternate row.There are various method of displaying different row in different color but here I’m going to use the most simple method using jQuery.
You can view the demo by clicking here.
I’m going to show you the examples both in “tables” and “div”.
First , define the tables and div as shown below in the “index.html” file,
<table border="1"> <tr><td>Michael</td></tr> <tr><td>Sam</td></tr> <tr><td>John</td></tr> <tr><td>Jason</td></tr> </table> <div>Michael</div> <div>Sam</div> <div>John</div> <div>Jason</div>
Now, we need to write the script for displaying the different color in the alternate row,
<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
//for div
$("div:odd").css("background-color", "#F4F4F8");
$("div:even").css("background-color", "#EFF1F1");
//for table row
$("tr:even").css("background-color", "#F4F4F8");
$("tr:odd").css("background-color", "#EFF1F1");
});
</script>
The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements.As you can see above the background color of the odd and even “div” are changed using the “css” method and “odd” and “even” filters of jQuery and the same applies for the even and odd “tr” which means for the row of table.
You can download the full source code
Popularity: 10% [?]
Follow me on twitter at http://twitter.com/roshanbh.
Related Posts
» Jquery : Benefits, Examples and Free Ebook
» jQuery is the most popular JavaScript and Ajax Framework
» Flashing Alert Message Box using JQuery
» Top Floating message box using jQuery
Comments
5 Responses to “Display different color in alternate row using jquery”
Leave a Reply






[...] Displaying different color in alternate row using jquery By Roshan Most of the tabular data are organized in such a manner that they are easy to read. And for this, most of the developers use different color to highlight the different row.There are various method of displaying different row in … Roshan Bhattarai’s Blog - PHP… - http://roshanbh.com.np [...]
Thank you very much, but where can I fine the jquery.js File ?
go to jquery.com and downaload the latest jquery.js file…..
Thank you for this post. Can you please explain how to restrict the effect to only divs inside, for example div id=”container”? So that it does not affect every div on the page?
let’s suppose that you’ve defined same class “alternate” then you can define the alternate color as
$(”.alternate:odd”).css(”background-color”, “#F4F4F8″);
$(”.alternate:even”).css(”background-color”, “#EFF1F1″);