Introduction To jTemplates - A jQuery and JavaScript Template Engine

jTemplates is a great lightweight template engine for jQuery and JavaScript. It allows you to process data (e.g. JSON data returned from an AJAX call) and feed it ito a template definition rather than manually building your html elements.

jTemplates supports foreach, for, if..elseif..else constructs in additional to parameters, nested templates etc.

The example below defines a template to display a list of orders and for each order the list of items that belong to that order. It shows how nested foreach can be used. The project documentation goes into more detail.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="js/jquery-jtemplates0.7.8.js" type="text/javascript"></script>
   
    <title>jTemplates Demo</title>
   
    <script type="text/javascript" language="javascript">
        // define some sample data orders
        var sampleOrder1 = {
            orderID: 'OR0001',
            orderItems: [
                { product: 'Apple', quantity: 23 },
                { product: 'Kiwi', quantity: 13 },
                { product: 'Orange', quantity: 2 },
                { product: 'Mango', quantity: 99 }
            ]
        }
        var sampleOrder2 = {
            orderID: 'OR0002',

            orderItems: [
                { product: 'Pear', quantity: 2 },
                { product: 'Mango', quantity: 400 }
            ]
        }

        // define a list of (2) sample orders
        var sampleOrdersList = {
            orders : [sampleOrder1, sampleOrder2]       
        }

        // When the DOM is ready apply the jTemplate
        $(document).ready(function() {
            // Tell jTemplates we want the div with the ID of renderedContentWillGoHere
            // to be filled with the templated
            $('#renderedContentWillGoHere').setTemplate($('#ordersListTemplateDefinition').html());

            // Combine the data in sampleOrdersList with the templateand render
            $('#renderedContentWillGoHere').processTemplate(sampleOrdersList.orders);
        });
   
    </script>
   
   
   
   
    <script type="text/html" id="ordersListTemplateDefinition">
   
        <!-- iterate over all the orders that were passed in as data
             and as each order is processed we give it an alias of currentOrder -->
        {#foreach $T as currentOrder}
   
            <!-- Output the orderID for the currentOrder we are iterating -->
            <h1> Order ID: {$T.currentOrder.orderID} </h1>
           
           
            <!-- Now we have a nested loop where we output the orderItems for the currentOrder -->
            <h4>Order Items</h4>           
            <ul>
                {#foreach $T.currentOrder.orderItems as currentOrderItem}
                    <li>{$T.currentOrderItem.product} {$T.currentOrderItem.quantity}</li>
                {#/for}
            </ul>           
           
        {#/for}
       
    </script>
       
</head>

<body>
    <div id="renderedContentWillGoHere"></div>
</body>

</html>

SHARE:

A Bouncing Ball Animation in jQuery

Out of the box and without plug-ins, you can animate elements with basic jQuery. You can view a live example of the following code which animates the position of a "ball" up and down.

There are a number of overloads for the jQuery animate function, the one used in this example takes 4 parameters:

  1. params: numeric property value(s) you want changed over time as the animation runs;
  2. duration: how long the animation takes ("slow", "normal", "fast", or number of milliseconds);
  3. easing: "linear" or "swing";
  4. callback: a function to be called when the animation finishes.

For example:

$("#ball").animate({ top: "1px" }, "slow", "swing", animDown);

This code changes the top property "slow"ly to a value of 1px whilst creating a non-linear "swing" motion. When the value of top reaches 1px, the animation has completed and the callback function animDown is called.

In the code below, the continuous bouncing is achieved by having 2 separate animation functions defined: animUp and animDown. Once the animUp animation completes it calls the animDown function and vice versa.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Bouncing Ball Animation in jQuery</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">

        /* Entry point into the animation 'loop'. Once the the animation is complete
           i.e. the ball is at the top, the animate call the callback function animDown */          
        function animUp() {
            $("#ball").animate({ top: "1px" }, "slow", "swing", animDown);
        }

        /* Called when the up animation completes. Once this downanimation is complete
           i.e. the ball is at the bottom, the animate function calls the callback function
           animUp */
        function animDown() {
            $("#ball").animate({ top: "446px" }, "slow", "swing", animUp);
        }

   
        $(document).ready(function() {
            animUp();
        });
       
    </script>

</head>
<body>
    <div><h1>Bouncing Ball Animation in jQuery</h1></div>
   
    <div id="ballContainer" style="width: 500px; height: 500px; display:block;
        background-color: White; border-bottom: solid 10px Black;">
       
        <div id="ball" style="position: relative; overflow: hidden;
            background-color: Transparent; color: Black; font-size: 50pt;
            top: 450px; left: 225px;">
            O
        </div>
       
    </div>
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired">Don't Code Tired</a></h4>
</body>
</html>

SHARE:

The Toggle Function in jQuery

jQuery's Toggle function allows you to specify 2 or more functions to be called alternately on each click. Specifying 2 functions you can create a simple 2 state toggle.

The example below (see live example) specifies 3 functions to count 1,2,3,1,2,3,1...etc. Each mouse click executes the next successive function, when the last function is reached, the cycle returns to the first function.

The jQuery selector ":button[name='btnCount']" means "select all buttons or input elements of type button that also have the name of btnCount".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>The Toggle Function in jQuery</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            $(":button[name='btnCount']").toggle(function() {
                $("#number").text("1");
            }, function() {
                $("#number").text("2");
            }, function() {
                $("#number").text("3");
            });

        });
    </script>

</head>
<body>
    <h1>The Toggle Function in jQuery</h1>
    <div id="number" style="font-size: 36pt; font-weight: bold;">
    </div>
    <input type="button" name="btnCount" value="Count" />
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired">Don't Code Tired</a></h4>
</body>
</html>

SHARE:

Maintaining Basic State With jQuery And CSS

When working on the client, you may have a number of HTML elements that have some form of logical state, e.g. coins (heads/tails), cards (face up/down), importance (high, medium, low), etc.

You could declare a variable for each element (or an array); when the use changes the state you update the variable representing the elements state and perform any UI changes.

An alternative to this which removes the need for additional variables is to represent the state of the element by which CSS classes are currently added to it.

The example below (view live example) shows one way to achieve this using jQuery. It represents a number of simulated coins and if each coin's state is heads or tails.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Maintaining basic state with jQuery and CSS</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnClick").click(function() {
                /* Select every element that has the CSS class coin applied
                   and iterate using the each function */
                $(".coin").each(function() {
                    /* Check the each element to see if it has a tails or heads
                       css class, and 'flip' the class and the text from T->H */
                    if ($(this).hasClass("heads"))
                        $(this).removeClass("heads").addClass("tails").text("T");
                    else if ($(this).hasClass("tails"))
                        $(this).removeClass("tails").addClass("heads").text("H");
                });
            });
        });
    </script>

    <style type="text/css">
        .coin
        {
            background-color: Silver;
            font-size: 24pt;
            font-weight: bold;
            padding: 5px;
        }
        /* We don't have to define .heads and .tails to make use of
        the state maintenance, but they are defined here for visual cues */
        .heads
        {
            color: Black;
        }
        .tails
        {
            color: White;
        }
    </style>
</head>
<body>
    <h1>Maintaining basic state with jQuery and CSS</h1>
    <span class="coin heads">H</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <h4>H = heads, T = Tails</h4>
    
    <form action="#">
    <input type="button" id="btnClick" value="Flip Coins" />
    </form>
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired" >Don't Code Tired</a></h4>
</body>
</html>

SHARE:

Basic Element Visibility in jQuery

Out of the box, jQuery comes with basic methods to show and hide elements. There is a live example here of the functions listed in this post.

slideToggle slide the element up/down to hide.show. It handles the toggle state automatically so you don't need to define a separate state boolean.

$("#content").slideToggle("slow");

toggle fades and shrinks the element to the upper left, again toggle state is handled automatically.

$("#content").toggle("slow");

fadeIn and fadeOut perform a fade and collapse/expand the element.

$("#content").fadeIn("slow");
$("#content").fadeOut("slow");

 

In the above examples the parameter "slow" can also be set to "normal", "fast" or a number in milliseconds.

SHARE:

A Simple Menu Roll-over using jQuery and CSS

The following ASP.NET page shows a simple example of a menu created using a combination of CSS and jQuery.

The menu is defined as an unordered list (which makes semantic sense) and styled with CSS (a real web site would of course have its CSS defined in external file(s)). When the user moves the mouse over a menu item, a CSS class is dynamically added; then removed when the mouse leaves. In addition a simple "infobox" span is defined whose text is changed to that of the title attribute of the <a> element.

There are lots of examples of image based roll-overs, this one is really cool and based on a simple idea.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <title>Simple jQuery Menu Example</title>

    <script type="text/javascript">

        var menuPrompt = "Please select a page to view."; // simple prompt for user
       
        $(document).ready(function() {

            // initialise the infobox prompt
            $("#infobox").text(menuPrompt);
       
            $(".nav_menu_list li a")
            .mouseover(function() {
                // add the mouseover style
                $(this).addClass("nav_menu_item_mouseover");
                // set the text of the infobox span to the anchor title attribute
                $("#infobox").text("Go to " + $(this).attr("title"));
            })
            .mouseout(function() {
                //remove the mouseover style
            $(this).removeClass("nav_menu_item_mouseover");
                // reset the text of the infobox span to user prompt
                $("#infobox").text(menuPrompt);
            })
        })
   
    </script>

    <style type="text/css">
        .nav_menu_list
        {
            list-style-type: none;
            margin: 0 0 0 21px;
            padding: 0;
        }
        .nav_menu_list li
        {
            float: left;
            text-align: left;
        }
        .nav_menu_list li a
        {
            display: block;
            padding: 0 10px 0 5px;
            text-decoration: none;
            font-size: 36pt;
        }
        .nav_menu_item_notmouseover
        {
            color: #0000FF;
            background-color: White;
        }
        .nav_menu_item_mouseover
        {
            color: White;
            background-color: #ec1c24;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul class="nav_menu_list">
            <li><a title="Page 1" href="#" class="nav_menu_item_notmouseover">Page 1</a> </li>
            <li><a title="Page 2" href="#" class="nav_menu_item_notmouseover">Page 2</a> </li>
            <li><a title="Page 3" href="#" class="nav_menu_item_notmouseover">Page 3</a> </li>
        </ul>
        <div style="clear: both;">
            <span id="infobox"></span>
        </div>
    </div>
    </form>
</body>
</html> 

SHARE:

Changing background image on <body> element with jQuery when using ASP.NET master pages

If you have an ASP.NET master page defined as below which specifies a css class for the body element to generate a background image for the whole page, you might want to override the default background on specific pages.

One way to accomplish this is to use jQuery to replace the css class that is being applied to the <body> element.

The master page below declares 2 ContentPlaceHolder controls; the first (ID="head") exisist within the <head> element, the second (ID="MainContentPlaceHolder") exists within the main body of the page.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
   
    <script type="text/javascript" src="jquery-1.3.2.js" ></script>
   
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
   
</head>

<body class="defaultbodybackground">
    <form id="form1" runat="server">  
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>

</html>

 

 
In one of our child pages we could add the following:


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script type="text/javascript">

           $(document).ready(function() {
               $("body").removeClass("defaultbodybackground");
               $("body").addClass("newbodybackground");
           })
        
        </script>
</asp:Content>


When the page is loaded, the above jQuery JavaScript runs and replaces the class "defaultbodybackground" with the page specific "newbodybackground".

A cool thing about jQuery is that you can have multiple $(document).ready() defined - for example you could also have some jQuery defined in the master page.

SHARE: