Thursday, November 12, 2009

jQuery How to build a simple table style switcher


  1. Get Started
    Let's create an html table that is showing some sample data. Here is it:

    <table>
    <tbody>
    <tr>
    <th>
    Column1
    </th>
    <th>
    Column2
    </th>
    </tr>
    <tr>
    <td>Data1.1</td>
    <td>Data2.1</td>
    </tr>
    <tr>
    <td>Data1.2</td>
    <td>Data2.2</td>
    </tr>
    </tbody>
    </table>



  2. Let's Add some style to it
    Let's add some simple styling to the table so it looks pretty! here is the css:

    table{width:400px;border:solid 1px black;}
    th {background:black;color:White;}
    td {color:Black;}



  3. Thinking about multiple styles of table
    Let's add an id to table and change some things in our css to make it more
    specific.
    HTML:

    <table id="my-table" class="my-table">
    <tbody>
    <tr>
    <th>
    Column1
    </th>
    <th>
    Column2
    </th>
    </tr>
    <tr>
    <td>Data1.1</td>
    <td>Data2.1</td>
    </tr>
    <tr>
    <td>Data1.2</td>
    <td>Data2.2</td>
    </tr>
    </tbody>
    </table>


    CSS:

    #my-table{width:400px;border:solid 1px black;}
    #my-table th {background:black;color:White;}
    #my-table td {color:Black;}


  4. Let's build another style
    Let's add another style to table. So now css looks like following:

    #my-table{width:400px;border:solid 1px black;}
    #my-table th {background:black;color:White;}
    #my-table td {color:Black;}

    #my-table-gray{width:400px;border:solid 1px gray;}
    #my-table-gray th {background:gray;color:White;}
    #my-table-gray td {color:gray;}



  5. Let's add jQuery to switch style!

    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
    <script>
    jQuery(document).ready(
    function() {
    jQuery("a").click(function() {

    var table = jQuery("#my-table")[0];
    if (table.className == "my-table")
    table.className = "my-table-gray";
    else
    table.className = "my-table";
    });
    }
    );

    </script>

    http://picasaweb.google.com/lh/photo/4KmKLPYDYIwzFS6BbNOfmg?authkey=Gv1sRgCJ2FjqX7hqreRw&feat=directlink

No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks