Friday, December 31, 2010

jQuery custom animation

jQuery and animation

The most common type of dynamic effect we'll want to perform is the simple show or hide element(s). This is all fine, but jQuery is capable of more complex type animations. In this tutorial we will create more complex (but in essence simple) animation that will show you common usage of animate() jQuery method.

I like to provide complete runnable example for completeness reason, so you can download it from my google code repository.

Basic animations

Before we start we will quickly show common jQuery animation method and their usage. The methods for showing and hiding elements are show() and hide. Using this methods, jQuery change HTML elements style.display property.

We use this methods like so:

$("h1").hide(); //This will hide all h1 elements.
  $("h1").show(); //This will show all h1 elements.

Simple as that! Also jQuery support toggling the display state of elements between revealed and hidden by providing us toggle method.


There is bit more to these methods than simple show/hide. When called with no parameters, these methods effect a simple manipulation of the display state of the wrapped elements. But when passed parameters, these effects can be animated so that the changes in display status of the affected elements take place over a period of time.

For example for following code:


will specify the duration of the effect and element will fade out slow. We can also use integer values here (these represent milliseconds). There are also predefined methods for this kind of fade in fade out effects: fadeIn(), fadeOut(), fadeTo(). We can use also slideDown(), slideUp() methods for gradually decreasing vertical size of element and thus remove it from display.

jQuery complex animation

Number of core effect method coming with jQuery is small. This should not be considered as jQuery handicap, because using jQuery animate() method writing our own animation is quite simple if you have rudimentary knowledge of CSS.

jQuery animate(properties, duration) method applies an animation as specified by properties. These properties are object hash that specifies the values that supported CSS style should reach at the end of the animation. The animation takes place by adjusting the values of the style properties from current value for element to the value for an element to the value specified in this object hash. duration optionally specifies the duration of the effect (same as in other simple methods).

Let see example:

$(function() {
   $("img[alt='arrow']").click(function(event) {
      var ball = $(this);                    
      var SCALE = 3;
        opacity: 'hide',
        width: ball.width()* SCALE,
        height: ball.height() * SCALE
       ball.animate({ opacity : 'show'}, 'fast');
       ball.animate({ top : '+=300'}, 4000);
       ball.animate({ left : '+=600'}, 4000);
       ball.animate({ top : '-=300'}, 4000);
         left : '-=600',
         width: '80px',
         height: '80px'

This example is simple to follow:
We have single image element in our DOM and we first (after user click on in) grab it's instance and named it "ball", then we hide use animate method (lines 5-10) to scale it by factor of 3 and fade it out. Then we show it (line 12), this will cause additional effect (some kind of blinking). Then we move ball into square (lines 13-22) and in the end we will revert ball's size in the same time we move it (lines 16-22).
You can see that we also use integer value for animation duration.

This is no complete tutorial and this animations method can be additionally configured by passing more parameters (like callback functions) and easing function (for animate method), but for this short example this was not necessary.

Here is ball animation in action:

Friday, December 24, 2010

Creating complete jQuery plugin


jQuery promote writing reusable components as jQuery plugins. This is good practice and a smart way of working. Also jQuery promotes a certain style for writing these plugins. This short example is simple guideline that show how to do this.


You can download simple example (that include complete Java web application and jQuery plugin that uses Ajax) from my google code repository.

This example is composed of single JSP page that show programming languages names and by clicking on some language we get description of that language in the bottom of page by pulling it from server using Ajax.

1.Naming conventions.

The recommendation is simple: prefix the file name with jQuery, then follow that with the name of the plugin, optionally include version number of the plugin, conclude it with .js.

We named our plugin "details" (because it show details about some programming language, I know it's stupid...but what can you do! :) ) and we named file jquery.cwp.details.js. Here we added unique plugin name to our self (cwp stands for "coding with passion") and limiting name conflict problems.

Similar consideration need to be taken with the names we give to our function. In our case we did not bother with that because there is 100% chance that this plugin will be used by me and only me and I probably will never use it again (outside of this example) there you go.

2.Handle $ alias properly.

We have no way of knowing weather a web developer (using out plugin) use $.noConfilct() function to allow the $ to be used by another library, so we need to guard ourself for such situation. We can use following trick to do so:

(function($) {
  //plugin impl.

By passing jQuery to a function that defines the parameters as $, $ is guaranteed to reference jQuery within the body of the function.

3.Complex parameter list.

Most plugins tend to be simple affairs that require few, if any, parameters. Intelligent defaults are supplied when optional parameters are omitted. The bind method is a good example; it the optional parameters are omitted, the listener function, which is normally specified as the third parameter can be supplied as the second.

We can use handy $.extend function to merge default parameter with optional. Consider the following show example:

function complex(p1, options) {
  var settings = $.extend({
    option1 : defaultVal1,
    option2 : defaultVal2,
    option3 : defaultVal3
  }, options||{});
  //"meat" of the function.

By merging the values passed by the web developer in the options parameter with an object containing all the available options with their default values, settings variable ends up with the default values superseded by any explicit values specified by the developer.

Note: With options||{} we guard ourself against options object that is null. or undefined.

4.Wrapper methods.

The true power of jQuery in the ability to easily and quickly select and operate on DOM elements. Luckily, we can extend that power by adding wrapper methods of our own. The general pattern of doing so is:

$.fn.functionName = function(params){function-impl};

That is almost it, just remember to always return (this) for chaining support. All that said, here is our function in all its glory :) :

(function($) {
    $.fn.details = function(url, options) {
        var settings = $.extend({
            customClass: null,
            paramName: 'language',
            url: url
        }, options||{}); {
            //substitute lt with appropriate start tag and gt with end tag...
            $('lt div gt')
            .addClass('details' +
                (settings.customClass ? (' ') + settings.customClass : ''))
                display: 'none'
                encodeURIComponent(settings.paramName) + '=' +
                function() {
        return this;

Transform XML into HTML using XSLT


XSLT stands for Extensible Stylesheet Language for Transformations. As you can see, there is no XML in name, and that is just strange if you
think about it, because XSLT is used for XML document transformation (transform input XML document into output (no necessary XML) document).
One of the advantage of parsing and handling XML documents with XSLT is that XSLT is W3C recommendation (so you have standard tool set and
concepts that are transferable).

Please download example from my google code repository:

XSLT: download
XML example file: download


XSLT language should be based on pattern matching. Most of your stylesheet consist of rules (called templates) used to transform
XML documents. Each rule says, "When you see part of a document that look like this (when you see specific tag in XML document), here's how you convert
it into something else.". XSLT is heavily influenced by the design of functional programming languages (Lisp, Scheme, F#, Haskel, ...).

You can think of templates as equivalent to functions in functional languages. In XSLT you do everything with recursion, as in any other F. language.

In oder to follow this tutorial, you need to understand what XML is all about. It is (XML) basically document that holds data and describe meaning of data. You can
describe data by defining schema's (similar to database schema's...).

When we create XML stylesheets we use two standards: XSLT and XPath. You can see my short XPath tutorial if you are not familiar with
this standard. There is also XQuery that is more similar to SQL, but we will not use it here.

There are number of free XSLT processors (Xalan, Saxon, Microsoft XSLT Processor, Altova XSLT Engine). We will use Altova XSLT Engine that is used
in their program XML Spy.


This tutorial will show how to transform XML to HTML file. We will use XML files from
US National Weather Service

They already include XSLT in their XML files, so you need to remove that file name and assign XSL file we will create here.

We will transform weather XML file in rather simple HTML file.

Here's how XML file look like:

You can see that this XML file is quite simple. Only one root element and bunch of child elements.

From this XML file we will create HTML page that looks like this:

You can see that page is also pretty simple. Only subset of elements are shown.

XSLT file for this page looks like this:

As you can see we are using XSLT 1.0 for browser compatibility reasons.

Line-by-line review:
4-6: We match root of the element and then apply templates for all other child elements.
8-17: Create HTML HEAD element and fill some styles.
18: Start BODY element filling.
20 and 24: Set some DIV's (not important)
21: Construct img element by combining two elements from XML.
25: We will not show all elements, we are interested only in "location", "observation_time", "pressure_string" and "wind_string".
30-34: For temperature element we will use special template.
35-37: For all other elements we will use same template. In this template we
use another template for extracting sensible name from XML element tag names (why not use it if they are mostly ok).
38-52: If element tag name contains "string" string then we will remove it. If element tag name contains only '_' char, then replace that char with space ' '. If this is not the case, then just return tag name. In this way we can use single template for processing all elements.

Ok that's it! Let's move on another tutorial...

Thursday, December 16, 2010

Recursion in XSLT


I like recursion! It is pure and formal. When you solve problems using recursion you code look cleaner & leaner & meaner! But problem with recursion is that
it is hard to imagine it. You can easily imagine how for loop works, but when you solve complex artificial intelligence algorithms using trees it can get
quite complex and error prone (min-max algorithms for example). I myself like to use recursion only when it might provide substantially more elegant
solution that other methods, and make recursion flow as easy to follow as possible (refactor it to special method,...).

That's all great, but in XSLT (like in any functional language) we are forced to use recursion in situations when we need create functions (templates)
that are not included in XSLT 2.0/1.0 spec. Also using recursion in XSLT is natural way of traversing XML (or any other tree like structured document).

To work with recursion in XSLT, you need to be familiar with couple of things in XSLT. First are off course templates. Templates are analog (or
at least similar) to functions in functional language (Scheme, LISP, F#,...). They have can have parameters and variables. Variables in XSLT are immutable
(they state cannot be changed after first value assignment). For example String object in Java is also immutable. Templates can call itself for recursive calls.
There are no loops in XSLT (don't try to find them). There is xls:forEach but it behave different than loops in imperative language.

Second thing is XPath. XPath is a syntax used to describe parts of XML document. XPath is designed to be used inside an attribute in XML
document. The syntax is a mix of basic programming language expressions and Unix-like path expression.


To show how process XML document using XSLT and recursion we will use example XML document. This document describes F1 2010 season overview for four races.
It shows name of grand Prix (race), data of race, winning driver name, winning team name, no of laps, winning time.

  Fernando Alonso
  Jenson Button
  Sebastian Vettel
  Jenson Button

We will transform this XML document into another document. The customer want to have data within same XML element (tag) put into single XML element
separated by comma. It is maybe strange request, but it is constructed like that to show how recursion is used in XSLT.

Example of transformated XML:

 Bahrain, Australia, Malaysia, China
 14/03/2010, 28/03/2010, 04/04/2010, 18/04/2010
 1:39:20.396, 1:33:36.531, 1:33:48.412, 1:46:42.163


You can download full file from my google code repository. Here I will attach image:

Recursion start at line 34. Here we create template with two parameters. First parameter is sequence (in XPath 2.0) or node-set (in XPath 1.0) of values we are going to traverse and concatenate with delimiter. Second parameter is resulting string that is printed at the end of template (line: 48) (at the end of recursion).
38 check if recursion should stop. It stops if there are no values left (or there was no values at first place) in sequence.
If sequence is not empty, then we go into recursion and call template (line: 40) again with following parameters:
41: Rest of values in sequence (everything after the first item -- position() > 1).
42: Concatenate first value from sequence into resulting string (we only handle first value differently).


Monday, December 13, 2010

Ajax tutorial with jQuery


AJAX is just simple technique for refreshing browser DOM with data acquired from some kind of server (Servlet/JSP, PHP, ASP.NET, ...). There is nothing specially clever in this technique.

Ajax is a less recent addition to the web toolbox than many people may realize. In 1998, Microsoft introduced the ability to perform asynchronous request as an ActiveX control (part of Outlook Web Access ).

After few years MS browser introduced standardized XMLHttpRequest (those days everything was flavored with XML :) ) object. These days you will not use XML with AJAX requests (rather JSON, or simple HTML). Google coined the term AJAX (Asynchronous JavaScript and XML -- you see!) and rest is history.

You can download example from this tutorial from my google app code SVN repository.

Plain JavaScript VS jQuery

Using plain JavaScript to implement AJAX (all cross browser JavaScript stuff) is not so easy. In a perfect world, code written for one browser would work in all commonly used browsers. But we do not live in perfect world and in this situation IE is one browser that handle AJAX in different way. The main problem is to create and instance of XMLHttpReauest object.

Let I give you some quick insight what you need to do in other to (just) get instance of this object in plain (cross browser) JavaScript:

var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
else  if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
else {
  throw new Error("This browser is not ajax enabled.");

There are couple of things you need to consider when you handle AJAX using plain JavaScript. One is encoding, another is creating handler for response...and so on.

Now, the jQuery code for AJAX request and getting response is as follows:


I think we have a winner! So we will be using jQuery from now on and leveraging it great capabilities.

jQuery load() method

Perhaps the most common uses of Ajax is to grab a chunk of content from the server and stuff it into the DOM as some strategic location. jQuery do just that, it's "load" html code into wrapper set using (go figure!) load() method. It sound simple and it is simple!

Let's go straight to the example:

We have page select component with F1 race drivers names filled in. When you change driver name, his details will be pulled from server and appended to DOM without page refresh. Interesting detail in this example is that select HTML component is also populated using Ajax.

Code for initial page DOM:

Now I will show you code for Ajax stuff and explain afterwards.

$(function() {

    $('#driverSelectionControl').change(function(event) {
             {driverId : $(});

02: Loading options html components into select component. You see how easy is to use Ajax with jQuery! :) We just need to give URL to JSP page.

Here is JSP page for driver list:

That's it. All that this JSP page do is rendering options components.

04-08(from previous example): Here we handle change event. When user select another driver (value is changed), then we load his detail from driversDetails.jsp. We pick user by passing parameter (driverId) to JSP page.

Here what JSP page look like:

<%@taglib prefix="c" uri="" %>


Driver name ${}
Team name ${}
Podiums ${item.podiums}
Points ${item.points}
Date of Birth ${item.birth}

You can use POST (default) or GET HTTP request method using load method. If you want to use POST (like in this example) then you send object hash as parameter to load (for example: {driverId : 205} ). If you want to initialize GET request, then you need to pass query string. If you use GET, you must ensure that your string is properly formated (names and values are URI-encoded).

If you are wondering when to use POST and when to use GET then follow this recommendations:

Use GET request when request operation that is made again and again make no change to state of server (for example when you just pulling data from server). This mean that our example is in opposite to this recommendation!
Use POST request when operation your request is initiating is non-idempotent (as opposite to idempotent like in GET). This mean, that you should use POST when you change some state on server (changing, or updating the data).

Other jQuery Ajax methods

jQuery include other methods for Ajax functionality like $.get(), $.post() for explicit GET or POST request operations.

jQuery also provides a general utility function for making Ajax requests, named $.ajax(). Under the covers, all other jQuery features uses this function. It it quite powerfull, but also complex. Feel free to investigate this function if you are interested.