Friday, January 22, 2010

Theme your table with jQuery UI

jQuery UI is a big treasure for the developer without any web designer behind in a small project. They provides a lot of widgets with many themes will make your UI less ugly:)

Unfortunately, there is no table widget available from jQuery UI. The jqGrid is great, but it is too heavy for me which only just on the purpose of show data. In this post, I will show you how to reuse jQuery UI's css to keep your table match theme. It is mostly done by JavaScript and leave your code clean.


1. CSS
The css classes will be used from jQuery UI are, ui-state-default (for th) ui-state-hover (for hover), ui-state-highlight(for row selection), ui-widget-content (for td).
Note: It is better to set your td :

td{font-weight: bold;}

. This is because jQuery UI's ui-state-hover setfont weight to bold. If your td's text is not, your will feel dizz cause the column size change when hover.

2. JavaScript
We need to add css style for th,td. And handle the hover, click event to add state style.

$().ready(function(){
$(".jtable th").each(function(){

$(this).addClass("ui-state-default");

});
$(".jtable td").each(function(){

$(this).addClass("ui-widget-content");

});
$(".jtable tr").hover(
function()
{
$(this).children("td").addClass("ui-state-hover");
},
function()
{
$(this).children("td").removeClass("ui-state-hover");
}
);
$(".jtable tr").click(function(){

$(this).children("td").toggleClass("ui-state-highlight");
});

});

7 comments:

suren said...

really nice ,hepled me a lot thanks

Dragnovich said...

I find this example very helpfull, how ever I dont like all my fields data in BOLD (if I need something in bold I use B tab, any way is true that colums size change on roll over so inestead of making all TD bold, I preffer to making ALL .ui-state-hover states INSIDE the table Not bold

.jtable tr .ui-state-hover {
font-weight: normal;
}

That solved the problem

whittet said...

I created a Live Demo using jsFiddle.net. Changes made to allow easy reuse of this behavior. Just add class jtable to your table and call the JTable.Setup() after your table is output.

Shane Whittet

Lav G said...

Nice. We can use this technique to do conditional formatting on the table resulting more intuitive UI.

Ricardo Cardoso said...

Beautiful and very useful! Thank you.

Unknown said...

thankq !!

kiri said...

thanks for the solution.