Monday, September 10, 2007

Adding visual effects to Ajax calls

A common pattern in Ajax-powered web applications is give the user a hint when a change happens. My prefered way to do this is using Prototype and Scriptaculous libraries and, obviously, Cake’s own Ajax helper.

This is something very basic, but I don’t think it has been already blogged elsewhere.


if you don’t know the basic functionality of the Ajax helper, you gotta read Graham Bird’s tutorial first.


Let’s start with some basice view code


this text is going to be replaced with the result of the Ajax Request


As you have already guessed, the update key of the options array refers to the DOM element that is going to be replaced with the ajax response and the value of the complete key is a javascript function that is going to be executed after the ajax update completes.

Now we have to write the gui.updateContent function:


var gui={
updateContent:function(){
$('content').visualEffect('Highlight');
}
}

I like to have a common.js file where I write all this appwide functions. Be sure to include it along with the last version of prototype and script.aculo.us in your layout.

What this function does is very simple. The dollar ($()) acts as a shorthand for document.getElementById() and returns de DOM element with the specified id, content, in this case.

The method visualEffect is an addition of the Script.aculo.us library to the Element object. So, we can concatenate it with the element returned by the dollar function. In this case, we’ll be caling the Higlight effect, also known as The Yellow Fade technique to let the user know that something has changed.

Now, let´s think that for some weird reason, you don’t want to let the user click on that link again. What needs to be done? Well, let the happy link fade into the nothingness.

Change our function to this:


var gui={
updateContent:function(){
$('content').visualEffect('Highlight');
$('link').visualEffect('Fade');
}
}

Now, our user will see the link slowly say goodbye forever…until the next reload. I think that would be pretty cool for a voting system. Don’t you think?

Well, for now that’s all folks.

No comments:

About Me

Ordinary People that spend much time in the box
Powered By Blogger