Tuesday, December 7, 2010

Easy table beautifier by jQuery UI CSS framework

jQuery is simple and powerful. When combine with jQuery UI and its CSS framework and ready made theme, we can get good looking UIs without any experiences in graphic design.


Today, I am going to show the easy way to make your plain and boring table look great just like one of jQuery UI widget.
Before

Sample code: test.html
--
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript' src='js/jquery-ui.min.js'></script>
<link href='css/ui/redmond/jquery-ui.css' type='text/css' rel='stylesheet' />
<script>
$(function(){
$('table').addClass('ui-widget-content').find('td').css({padding: '2px'});
$('tr:has(td):odd').addClass('ui-state-default');
$('tr:has(td):even').addClass('ui-state-focus');
$('tr:has(th)').addClass('ui-widget-header');
});
</script>
</head>
<body>
<table>
<tr><th>#</th><th>Name</th><th>Age</th></tr>
<tr><td>1</td><td>Mr. AAAAAA</td><td>25</td></tr>
<tr><td>2</td><td>Mr. BBBBBB</td><td>18</td></tr>
<tr><td>3</td><td>Mr. CCCCCC</td><td>27</td></tr>
<tr><td>4</td><td>Mr. DDDDDD</td><td>24</td></tr>
<tr><td>5</td><td>Mr. EEEEEE</td><td>35</td></tr>
<tr><td>6</td><td>Mr. FFFFFF</td><td>32</td></tr>
</table>
</body>
</html>

--
After

First we add class 'ui-widget-content' to a <table>. Alternatively, we add padding:2px to all <td> too. We separated table row into 2 kinds. First is a header row, rows with <th> inside and content row, rows with <td> inside.


For header rows with <th> inside, as jQuery selector "tr:has(th)", we apply "ui-widget-header" class to them. For content rows, to make odd and event rows look different, we apply different class to them identified by jQuery selector ":odd or :even".


That is it ! It is easy right ? I can surely make it look a bit better, with round corners and so on but this is enough to give you a picture of what you can do with jQuery CSS framework.

No comments:

Post a Comment