Rey Bango

Web developer, honey badger

Generic Activity Indicator for Ajax Requests

Over the weekend I was fiddling was some code to see how to make a generic activity indicator for Ajax requests. I’m sure most of you have seen these but if not, here’s one similar to what Facebook uses:

While it’s may not look like much, that animated .gif is pretty important because it tells a user that something is happening and that results will appear shortly. The last thing you want is for a user to think the page has locked up or broken and using this simple method advises them that their request is being processed.

Targeted Indicators

In my case, I was looking for a way to set an indicator within the specific DOM element that would be affected by the XHR call. So if my XHR call was to set the contents of a specific DIV, I wanted the indicator to render within that specific DIV only (similar to what Facebook does).

First, I created three DIVs and 3 anchor tags:

<a href="#">Box 1</a>|<a href="#">Box 2</a>|<a href="#">Box 3</a> 

<br /><br />

<div id="box1">&nbsp;</div>
<div id="box2">&nbsp;</div>
<div id="box3">&nbsp;</div>

and I set the DIVs to a specific width and floated them left:

#box1, #box2, #box3 { background-color:#E5EECC; border:1px solid #D4D4D4; width: 200px; float:left; };

Next, I created a new method called fillBox() that would take the target element’s ID and use that to dynamically create a new IMG tag and insert the activity indicator. What I decided to do was leverage jQuery’s global Ajax events to create the generic handlers for this. Using ajaxStart(), which fires off when an Ajax request is initiated, I dynamically create the tag for my activity indicator and inset it using the prepend() method:

		$(ele).ajaxStart( function() {
		
			$(this).prepend( "<img id='throbber' src='facebook.gif' />" );
		
		})

Then using the Ajax global event handler ajaxStop(), I would easily delete the indicator once the Ajax request was done by using the remove() method to delete the IMG tag from the DOM:

ajaxStop( function() {
		
	$("#throbber").remove();
		
});

Lastly, using some event delegation, I created an event handler for the clicks on the anchor tags:

$( "a" ).click( function(e) {
	
	var el = '';
	switch(e.target.text) {
		case "Box 1": 
			el = '#box1';
			break;					
		case "Box 2": 
			el = '#box2';
			break;								
		case "Box 3": 
			el = '#box3';
			break;										
	} 

	fillBox( el );
	
});

The handler simply looked for the anchor tag’s text and based on that filled a local var with the ID that would be targeted for the indicator. It then passed that ID to the fillBox() method.

A Little Roadblock

I thought I was done and the code look pretty straightforward. When I ran this, though, I experienced some odd behavior:

When I would click on the “Box 1″ link, the indicator would correctly appear in the first DIV followed by the data populating the box. When I would next click on the “Box 3″ link, though, both the first box AND the third box would have the indicators displayed! Not good.

I looked into it and got feedback from Adam Sontag who provided the answer I needed. I had incorrectly assumed that ajaxStop() would unbind the jQuery global Ajax events from the attached element. Unfortunately it doesn’t so by using the unbind() method, I was able to resolve the issue.

			
		$.ajax({
		  url: 'test.php',
		  cache: false,
		  success: function(data) {
			
			$(ele).html( data ).unbind( 'ajaxStart' ).unbind( 'ajaxStop' );

		  }
		});

	};

The Solution Gets Easier

Then I got more feedback from Karl Swedberg which really streamlined the whole thing. He recommended forgoing the Ajax global events altogether and simply inserting the indicator via my fillBox() method directly and since I was replacing the contents of the DIVs with the html() method, there was no need to use remove() since the IMG tag was already being removed.

var fillBox = function( ele ) {

	$(ele).prepend( "<img id='throbber' src='facebook.gif' />" );

	$.ajax({
		url: 'test.php',
		cache: false,
		success: function(data) {

			$(ele).html( data );

		}
	});

};

So while I initially was looking to use jQuery’s built-in global Ajax event handlers for making this generic, I’m finding Karl’s solution much cleaner. It requires less event handlers and method calls to do the same task. Love it!

Here’s the end result and you can see the demo here:

<!DOCTYPE html>
<html lang="en">
<head> 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <meta name="robots" content="noindex" /> 
  <title>Throbber Test</title> 
  <style>
	#box1, #box2, #box3 { background-color:#E5EECC; border:1px solid #D4D4D4; width: 200px; float:left; };
  </style>
  <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">

	fillBox = function( ele ) {

		$(ele).prepend( "<img id='throbber' src='facebook.gif' />" );

		$.ajax({
			url: 'test.php',
			cache: false,
			success: function(data) {

				$(ele).html( data );

			}
		});

	};
	
	$(document).ready( function() {
	
		$( "a" ).click( function(e) {
			
			var el = '';
			switch(e.target.text) {
				case "Box 1": 
					el = '#box1';
					break;					
				case "Box 2": 
					el = '#box2';
					break;								
				case "Box 3": 
					el = '#box3';
					break;										
			} 

			fillBox( el );
			
		});
		
	});
  </script>
  
</head> 
 
<body> 

<a href="#">Box 1</a>|<a href="#">Box 2</a>|<a href="#">Box 3</a> 

<br /><br />

<div id="box1">&nbsp;</div>
<div id="box2">&nbsp;</div>
<div id="box3">&nbsp;</div>

</body> 
</html> 

Video Interview with the Yahoo UI JavaScript Library Team

Last Friday I got a chance to visit the Yahoo! campus and meet with the YUI team. I have to say I felt pretty special because these guys usually work remotely on Friday’s and they took the time to come into the office to chat with me. I really appreciated that and I’m glad that this video will help put a face to the name of these JavaScript ninjas. A very special thanks to Eric Miraglia and Gonzalo Cordero for setting this up.

** NOTE: If for any reason you can’t see the video via the embedded player, just click the link below it to jump over to Vimeo.

Interview with the YUI Team from Rey Bango on Vimeo.

The YUI team spent some time with me to chat about the good stuff happening with YUI

jQuery Replacements for CFGRID, CFWINDOW, and CFTOOLTIP

Sean Corfield blogged about some new jQuery-based Ajax replacement widgets created by Michael Sprague.

Michael wrapped the functionality of FlexiGrid, jTip and jqModal (3 of the best jQuery plugins available) into easy to use ColdFusion tags that serve to replace CFGRID, CFWINDOW, and CFTOOLTIP.

I checked them out and Michael did an excellent job!

Thanks for finding this Sean.

Ext Releases v2.0.2 with Adobe AIR Support

To coincide with the release of Adobe's AIR v1.0, the Ext team released v2.0.2 of the Ext framework with enhanced support for the new AIR runtime. The Ext and Adobe teams collaborated during the AIR beta process to ensure that support for the updated AIR API and security sandbox would be available to Ext users from day one.

To demonstrate Ext's AIR capabilities, founder Jack Slocum went about updating the Simple Tasks application he initially created during the early AIR beta process.

Making extensive use of the newly updated AIR API, the Ext team enhanced the Ext.air package to handle such functionality as:

  • Managing native windows, event listeners and automatic state management for the windows.
  • Use of the new synchronous database access introduced in AIR beta 3.
  • Native drag and drop and clipboard access.
  • Playing sounds.
  • Minimizing AIR applications to the system tray.

Adding an icon to the system tray is now a trivial task as can be seen in this code sample:

var win = new Ext.air.NativeWindow({
    id: &apos;mainWindow&apos;,
    instance: window.nativeWindow,
 
    // System tray config
    minimizeToTray: true,
    trayIcon: &apos;ext-air/resources/icons/extlogo16.png&apos;,
    trayTip: &apos;Simple Tasks&apos;,
    trayMenu : [{
        text: &apos;Open Simple Tasks&apos;,
        handler: function(){
            win.activate();
        }
    }, &apos;-&apos;, {
        text: &apos;Exit&apos;,
        handler: function(){
            air.NativeApplication.nativeApplication.exit();
        }
    }]
});

In addition to demonstrating AIR apis, Simple Tasks v2 also includes several advanced samples to demonstrate creating custom Ext components. These samples include:

ListTree – Allows for a hierarchical list of options, similar to a treeview, but within a drop-down listbox

Custom Grid Columns – Allows for grid columns to be represented as buttons or menus

Switch – Provides a collection of buttons, one of which can be “pressed” at a time. This is used as an alternative for radio buttons.

Ext v2.0.2 is immediately available for download as is Adobe AIR v1.0

Adobe Release AIR v1.0! No More Beta!

Continuing their march into the RIA space, Adobe announced today the official release of AIR v1.0 and Flex 3.0.

Adobe AIR

The AIR runtime and SDK has gone through an especially long beta cycle (since June 2007) to ensure that both security and compatibility with existing frameworks was achieved. Some key new and/or updated features include:

  • Enhanced Desktop Fucntionality: Drag and drop to the operating system, copy and paste between applications, launching of AIR applications from the desktop or the browser, and run in the background with notifications.
  • Data Access: Adobe AIR now provides both synchronous and asynchronous access to the local file system, as well as structured data within a local database. This database is implemented using the open source SQLite database.
  • JS Library Support: Most major Ajax frameworks can be used to build AIR applications. Supported frameworks include jQuery, Ext JS, Dojo, and Spry. Adobe AIR integrates JavaScript and ActionScript to allow cross-scripting between the two languages, and integrated rendering of Flash and HTML content.
  • Security: Applications built on Adobe AIR can only be installed through a trustworthy install process that verifies that the application is signed via industry standard certificates, providing users with information about the source and capabilities of the application.

Flex 3.0

Adobe's Flash-based RIA development platform, Flex, continues to mature and has been picking up steam in both the corporate space as well as sites such as blist and Scrapblog who have embraced Flex whole-heartedly. Some of the new features in Flex 3.0 include:

  • Intelligent coding, interactive step-through debugging, and visual design of user interface layout
  • New capabilities for creating RIAs and building applications on Adobe AIR
  • Integrates with Adobe Creative Suite® 3 making it easy for designers and developers to work together more efficiently.
  • New testing tools, including memory and performance profilers and integrated support for automated functional testing, speed up development and lead to higher performing RIAs.

One of the most compelling parts of the Flex announcement is the fact that Adobe has released the Flex SDK under the open source Mozilla Public License.

Adobe is working hard to raise the bar in the RIA space by giving developers more tools with great functionality. 2008 is panning out to be an interesting year in web development.

Ext & ColdFusion Server-Side Community Projects

An excellent barometer of a project's growth and acceptance is the creation of community extensions that compliment the project. It's demonstrative of how users are embracing Ext and in some cases, need to go past what the core framework provides. It seems that almost on a daily basis, new extensions are contributed by volunteer Ext developers, most of which are of excellent quality and functionality.

Server-Side Initiatives

Ext is a client-side framework and is focused at providing a strong foundation for client-side developers. More and more, though, we're seeing demand from the server-side crowd to offer some form of support from within application server technologies such as ColdFusion, .Net, and Java. Another step forward in the community involvement model is when developers begin to offer integration capabilities for a framework into their own server-side environment. This is something that has really taken off and we've seen a number of server-side projects spring up to tackle this demand.

ColdFusion

With Ext v1.0 built into the Adobe ColdFusion 8 application server and powering most of the Ajax-enabled controls, it was obvious that sooner or later, CF developers were going to want to see how they could extend the built-in capabilities of these controls. Being Ext-driven, many developers soon realized that it was just a matter of looking at the Ext API documentation and leveraging the full capabilities of the Ext framework. Unfortunately, ColdFusion included Ext v1.0 which is substantially less feature-rich than Ext v2.0 and with no method of upgrading ColdFusion to the newest release, some very innovative developers took matters into their own hands and created extensions that provide a path to Ext v2.0. Following are three ColdFusion frameworks that have started the work of wrapping Ext into a server-side framework usable by all ColdFusion developers:

  • Ext.CFC – Created by Brian Love, this was the first notable component that tried to provide server-side integration with Ext. We posted about Brian's work on the Ext blog in early December.
  • cfExt – Dan Vega was next in line, coming up with a component class that would provide access to the Ext 2.0 windowing capabilities. Several iterations later and after a ton of community feedback, Dan released cfExt which has received a tremendous amount of positive feedback and support within the ColdFusion community.
  • ColdExt – The most recent addition, ColdExt by Justin Carter, takes a different approach using a tag-based implementation to expose the Ext API to ColdFusion developers. This is actually a great way of doing things since ColdFusion's language, CFML, is mark-up based and the use of a tag library should make it very intuitive for CF developers to use ColdExt

As of this writing, Dan and Justin have been in contact and may take steps to consolidate their efforts into one nice project.

ColdFusion-Powered JoesGoals.com Get's More Ajax Goodness

I just read that Ian Smith, creator of CF-Powered Joe's Goals, has given the site a bit of a face lift and has released v2.0 into closed beta.

This is a complete rebuild of the core application with an emphasis on speed, ease of use, and scalability. Here are the major changes currently in the testing version:

  1. Speed Speed Speed! 2.0 is a full Ajax application, no more waiting around for page refreshes.
  2. Improved stats including a longest chain stat for positive goals and longest gap stat for negative goals.
  3. Lighter design means there are less links to deal with and better clarity. Goals can now be edited by clicking on their name instead of on the options link.
  4. Customizable display options means you can pick which stats you want to watch for each goal.
  5. Printable tracker for those who like to work on a hard copy during the week and update their tracker on the weekend.
  6. You can also switch back and forth between 2.0 and the classic version until everyone gets ported over.

I'll be checking this update out as Ian has given me early access to it and writing up some feedback over on Ajaxian.com soon.

Ext 2.0 JavaScript Framework Beta 1 is just amazing

If you're a ColdFusion 8 developer, then you've probably used Ext by virtue of using CF8's Ajax controls. Well, Ext JS, LLC, the company that makes the Ext JavaScript framework has just released a new version.

The Ext team is proud to announce that Ext v2.0 Beta 1 is available for download. This release of the Ext framework features updated portal and desktop examples, documentation updates, and bug fixes.

New Sample Application Updates

In our last release, we introduced two new sample applications which were truly a hit with the development community. The two applications, Web Desktop and Customizing: Portals were excellent examples of the capabilities of the new Ext 2.0 framework. For the beta release, we have dramatically improved the features and functionality of both. The Web Desktop has been drastically enhanced to include a start menu as well as functional icons on the desktop. It truly looks like you're working within an operating system like Windows.

Web Desktop

This sample includes updates to the look, code organization, desktop shortcuts and an excellent StartMenu implementation contributed by Todd Murdock of the Ext community. Thanks also go to Todd for porting the tab scrolling code into the TaskBar so it can handle additional windows without creating additional rows of task items.

Portal

This sample received it's next major revision including new shortcut classes for columns and portlets, new layout enhancements and an overall smoother API for development.

All of the updated Ext 2.0 Beta 1 samples can be seen at the Ext 2.0 Samples page. Additional samples are available in SVN.

New API Documentation Updates

We're continuing our efforts to provide top-notch information and documentation for Ext developers. In addition to updating our documentation with new class information, we've enlisted the assistance of several community members in developing tutorials specific to Ext 2.0 and migrating existing tutorials to take into account changes in Ext 2.0.

As we mentioned in our last post, our documentation center has been dramatically revamped to help finding information substantially easier.

2.0 Migration

The Ext 2.0 migration guide is near completion and we will be proofreading it shortly to ensure that it meets our high standards of documentation. As soon as it's been verified, we will make it immediately available to help expedite the transition from Ext v1.x to Ext 2.0.

2.0 Availability

The Ext 2.0 codebase has stabilized and several clients have begun to use Ext 2.0 in production environments. Ext 2.0 is available for download and code updates are available to SVN subscribers in the Ext SVN under branches/ext2.0.

License

Ext 2.0 is being released with the same license options as 1.1. Please visit http://extjs.com/license for more details.

For many companies and products, Open Source licenses are not an option. Ext offers commercial licenses for these situations and for companies using Ext in commercial applications who want to help support the project. It is a non-copyleft license which gives companies complete freedom when integrating Ext in their products and web sites. During the 2.0 prerelease period, estimated until October 31st, we are offering a 25% discount on all commercial license purchases. If you were considering a commercial license, now is the time!

Adobe, you need to let us do this in CF8! :)

Man, now wouldn't this be a nice thing to have in CF8:

Ext 2.0 Web Desktop w/ Start Menu

The start menu mod was created by Ext community member mxracer.

Just awesome.

Ext 2.0 Alpha Released – New version of Javascript Framework

The Ext team is proud to announce that the first public release of Ext v2.0 is available for download. This new version of the Ext framework introduces a host of new features, a new document center, expanded & better organized samples and bug fixes. Another important aspect to note is that there has not been a significant library size increase in this new version.

New Features

In our last posting, we went into detail about some of the new features in Ext 2.0. Many of these features are unique to the Ext 2.0 framework and will make developing desktop-like application substantially easier. These include:

Along with the features list above, there are many additional features and architectural changes that make working with 2.0 more intuitive and flexible than previous releases. If you haven't tried 2.0 yet, you should. You won't be disappointed.

New API Documentation Center

We wanted to make traversing the Ext API as simple as possible and that prompted a substantive revamp of our document center. The new version continues to make use of the intuitive treeview metaphor but great expands on this by taking advantage of the new scrolling tabs feature being introduced in Ext 2.0. By selecting a specific API topic on the tree, a new tab will appear allowing developers to maintain multiple API documents open at one time instead of being limited to only one page at a time. A new search feature has also been added which acts to filter down the treeview based on a keyword entered into the search field.

In addition, each page now contains quick links which will immediately scroll the users down to view properties, methods and events of a specific class.

Finally, a new “Direct Link” feature greatly simplifies the ability to bookmark specific pages of the API by providing a permalink for specific sections of the documentation.

2.0 Migration

We are working on a 2.0 migration guide and several new tutorials that cover working with the new 2.0 component model, container and layout managers. We hope to have them available with the Beta 1 release.

New 2.0 Samples

Prior to this release, the demos for Ext were consolidated into the API viewer making it cumbersome to differentiate what was a demo and what was part of the API document viewer. We have now detached the demos and organized them onto a standalone page. The applications are also grouped into specific subsections to allow Ext developers to drill down into applications that show specific Ext functionality.

Portal Samples

Building dashboard-style applications similar to iGoogle or PageFlakes are all the rage so we've included a demo application as a foundation for building a portal application. The demo includes functionality for smooth repositioning of the portlets via drag and drop functionality and each portlet has the standard minimize and close functionality found in similar dashboard implementations. In addition, each portlet has a settings icon which is bound to a custom event handler and allows Ext developers to define behaviors that their users can apply to specific portlets.

Themes and Plugins Repository

User contributed Ext themes and extensions/plugins are an important aspect of the project allowing Ext developers to display their creativity by extending the Ext framework as well as leveraging new functionality not currently available in the library. Currently, these contributions are made via the support forum and are not posted in a way that makes finding specific functionality easy.

In an effort to organize these extensions, the Ext team is in the process of building a themes and plugins repository that will allow developers to submit the extensions and categorize them accordingly. Submitters will be able to give a good description of the extension as well as upload screenshots, all in an effort to make it easier for the community to find specific functionality.

More 2.0 Samples

All of the 2.0 samples can be seen at the Ext 2.0 Samples page. Additional samples are available in SVN.

2.0 Availability

The 2.0 codebase has stabilized and several clients have begun to use Ext 2.0 in production environments. Ext 2.0 is available for download and code updates are available to SVN subscribers in the Ext SVN under branches/ext2.0.

License

Ext 2.0 is being released with the same license options as 1.1. Please visit http://extjs.com/license for more details.

For many companies and products, Open Source licenses are not an option. Ext offers commercial licenses for these situations and for companies using Ext in commercial applications who want to help support the project. It is a non-copyleft license which gives companies complete freedom when integrating Ext in their products and web sites. During the 2.0 prerelease period, estimated until October 31st, we are offering a 25% discount on all commercial license purchases. If you were considering a commercial license, now is the time!

Sponsors



Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Categories

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache