JavaScript

How to Load In and Animate Content with jQuery

Tagged:  

If you are interested in writing an application with jQuery, but have not used the library before then you are probably looking for a few good tutorials. Over at NETTUTS they have put together a nice tutorial about loading and animating content with jQuery.

You can read an excerpt of the tutorial below.

Step 1

First thing's first, go and download the latest stable release of jQuery and link to it in your document:

<script type="text/javascript" src="jQuery.js"></script>

One of the best things, in my opinion, about jQuery is it’s simplicity. We can achieve the functionality described above coupled with stunning effects in only a few lines of code.

First let’s load the jQuery library and initiate a function when the document is ready (when the DOM is loaded).

$(document).ready(function() {
	// Stuff here
});

Step 2

So what we want to do is make it so that when a user clicks on a link within the navigation menu on our page the browser does not navigate to the corresponding page, but instead loads the content of that page within the current page.

We want to target the links within the navigation menu and run a function when they are clicked:

$('#nav li a').click(function(){
	// function here
});

Let's summarize what we want this function to do in event order:

  1. Remove current page content.
  2. Get new page content and append to content DIV.

We need to define what page to get the data from when a link is clicked on. All we have to do here is obtain the 'href' attribute of the clicked link and define that as the page to call the data from, plus we need to define whereabouts on the requested page to pull the data from - i.e. We don't want to pull ALL the data, just the data within the 'content' div, so:

var toLoad = $(this).attr('href')+' #content';

To illustrate what the above code does let's imagine the user clicks on the 'about' link which links to 'about.html' - in this situation this variable would be: 'about.html #content' - this is the variable which we'll request in the ajax call. First though, we need to create a nice effect for the current page content. Instead of making it just disappear we're going to use jQuery's 'hide' function like this:

$('#content').hide('fast',loadContent);

The above function 'hides' the #content div at a fast rate, and once that effect finished it then initiates the "loadContent" function (load the new content [via ajax]) - a function which we will define later (in step 4).

Step 3

Once the old content disappears with an awesome effect, we don't want to just leave the user wondering before the new content arrives (especially if they have a slow internet connection) so we'll create a little "loading" graphic so they know something is happening in the background:

$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');

Here is the CSS applied to the newly created #load div:

#load {
	display: none;
	position: absolute;
	right: 10px;
	top: 10px;
	background: url(images/ajax-loader.gif);
	width: 43px;
	height: 11px;
	text-indent: -9999em;
}

So, by default this 'load' span is set to display:none, but when the fadeIn function is initiated (in the code above) it will fade in to the top right hand corner of the site and show our animated GIF until it is faded out again.

Step 4

So far, when a user clicks on one of the links the following will happen:

  1. The current content disappears with a cool effect
  2. A loading message appears

Now, let's write that loadContent function which we called earlier:

function loadContent() {
	$('#content').load(toLoad,'',showNewContent)
}

The loadContent function calls the requested page, then, once that is done, calls the 'showNewContent' function:

function showNewContent() {
	$('#content').show('normal',hideLoader);
}

This showNewContent function uses jQuery's show function (which is actually a very boring name for a very cool effect) to make the new (requested) content appear within the '#content' div. Once it has called the content it initiates the 'hideLoader' function:

function hideLoader() {
	$('#load').fadeOut('normal');
}

We have to remember to "return false" at the end of our click function - this is so the browser does not navigate to the page

It should work perfectly now. You can see an example of it here: [LINK]

Here is the code so far:

$(document).ready(function() {

    $('#nav li a').click(function(){
    
    var toLoad = $(this).attr('href')+' #content';
    $('#content').hide('fast',loadContent);
    $('#load').remove();
    $('#wrapper').append('<span id="load">LOADING...</span>');
    $('#load').fadeIn('normal');
    function loadContent() {
    	$('#content').load(toLoad,'',showNewContent())
    }
    function showNewContent() {
    	$('#content').show('normal',hideLoader());
    }
    function hideLoader() {
    	$('#load').fadeOut('normal');
    }
    return false;
    
    });
});

Step 5

You could stop there but if you're concerned about usability (which you should be) it's important to do a little more work. The problem with our current solution is that it neglects the URL. What if a user wanted to link to one of the 'pages'? - There is no way for them to do it because the URL is always the same.

So, a better way to do this would be to use the 'hash' value in the URL to indicate what the user is viewing. So if the user is viewing the 'about' content then the URL could be: 'www.website.com/#about'. We only need to add one line of code to the 'click' function for the hash to be added to the URL whenever the user clicks on a navigation link:

window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);

The code above basically changes the URL hash value to the value of the clicked link's 'href' attribute (minus the '.html' extension. So when a user clicks on the 'home' link (href=index.html) then the hash value will read '#index'.

Also, we want to make it possible for the user to type in the URL and get served the correct page. To do this we check the hash value when the page loads and change the content accordingly:

var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
    var href = $(this).attr('href');
    if(hash==href.substr(0,href.length-5)){
        var toLoad = hash+'.html #content';
        $('#content').load(toLoad)
    } 
});

With this included here is all the javascript code required: (plus the jQuery library)

$(document).ready(function() {
	
    // Check for hash value in URL
    var hash = window.location.hash.substr(1);
    var href = $('#nav li a').each(function(){
        var href = $(this).attr('href');
        if(hash==href.substr(0,href.length-5)){
            var toLoad = hash+'.html #content';
            $('#content').load(toLoad)
        } 
    });
    
    $('#nav li a').click(function(){
    
    var toLoad = $(this).attr('href')+' #content';
    $('#content').hide('fast',loadContent);
    $('#load').remove();
    $('#wrapper').append('<span id="load">LOADING...</span>');
    $('#load').fadeIn('normal');
    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
    function loadContent() {
    	$('#content').load(toLoad,'',showNewContent())
    }
    function showNewContent() {
    	$('#content').show('normal',hideLoader());
    }
    function hideLoader() {
    	$('#load').fadeOut('normal');
    }
    return false;
    
    });
});
You can read the full tutorial here.

jQuery is one of the best JavaScript/Ajax libraries that I've seen, so it is always good to see more tutorials using the library. If you haven't used jQuery before then I would recommend using it and this tutorial is a great place to start.

Title Capitalization in JavaScript

John Resig has written a good JavaScript port of the excellent Perl script written by John Gruber that provides pretty capitalization of titles. It is amazing how well the script works for capitalizing words.

Below is an excerpt from the post.

The excellent John Gruber recently released a Perl script which is capable of providing pretty capitalization of titles (generally most useful for posting links or blog posts).

The code handles a number of edge cases, as outlined by Gruber:

  • It knows about small words that should not be capitalized. Not all style guides use the same list of words — for example, many lowercase with, but I do not. The list of words is easily modified to suit your own taste/rules: "a an and as at but by en for if in of on or the to v[.]? via vs[.]?" (The only trickery here is that “v” and “vs” include optional dots, expressed in regex syntax.)
  • The script assumes that words with capitalized letters other than the first character are already correctly capitalized. This means it will leave a word like “iTunes” alone, rather than mangling it into “ITunes” or, worse, “Itunes”.
  • It also skips over any words with line dots; “example.com” and “del.icio.us” will remain lowercase.
  • It has hard-coded hacks specifically to deal with odd cases I’ve run into, like “AT&T” and “Q&A”, both of which contain small words (at and a) which normally should be lowercase.
  • The first and last word of the title are always capitalized, so input such as “Nothing to be afraid of” will be turned into “Nothing to Be Afraid Of”.
  • A small word after a colon will be capitalized.

He goes on to provide a full list of edge cases that this script handles.

You can read the full post here.

I can see some uses for this script in applications that would like to take user input and make it into a properly formatted title. This could be handy in a del.icio.us or digg like application.

Processing JavaScript

Tagged:  

A while back I wrote a post about Processing (you can read my previous post here). If you haven't seen Processing before, it is a Java based development platform that rivals Flash. Well, John Resig has written a cool port of the Processing API to JavaScript.

Below is an excerpt from John's post.

The Processing Language

The first portion of the project was writing a parser to dynamically convert code written in the Processing language, to JavaScript. This involves a lot of gnarly regular expressions chewing up the code, spitting it out in a format that the browser understands.

It works "fairly well" (in that it's able to handle anything that the processing.org web site throws at it) but I'm sure its total scope is limited (until a proper parser is involved). I felt bad about tackling this using regular expressions until I found out that the original Processing code base did it in the same manner (they now use a real parser, naturally).

The language includes a number of interesting aspects, many of which are covered in the basic demos. Here's a brief selection of language features that are handled:

  • Types and type casting - Type information is generally discarded, but becomes important in variable declaration and in casting (which is generally handled well).
  • Classes - The full class system is supported (can be instantiated, etc. just fine).
  • Method overloading and multiple constructors - Within classes you can have multiple method (or constructor) definitions - with the appropriate methods being called, based upon their signature length.
  • Inheritance - Even classical-style inheritance is supported.

Note: There's one feature of Processing that's pretty much impossible to support: variable name overloading. In Processing you can have variables and functions that have the same name (e.g. float size = 0; float size(){}). In order to support this there would have to be considerable overhead - and it's generally not a good practice to begin with.

You can read the full post here.

If you get some time over the weekend, you might want to play with the new Processing JavaScript API. This looks like another good job by John Resig.

Wolfenstein 3D in JavaScript

Tagged:  

If you are looking for something to get through the rest of the work week then check out this great JavaScript game. The game is Wolfenstein 3D (for you younger readers Wolfenstein 3D was the very first big first person shooter) and is just like the game I used to play on my 386 (except the AI is not finished)!

You can read more about the game here. Or you can get straight to the game here.

Note: that the game works on most browsers, but does not work on Internet Explorer.

It is always interesting to see things like this done in JavaScript. Who knows, perhaps we will be playing games like Doom (the original version) in JavaScript within the next few years.

TubeSpy adds support for 11 languages

TubeSpy, our YouTube application from Ajaxonomy Labs, now supports 11 new languages. By utilizing the Google Language API, TubeSpy is now able to dynamically change the language used in the application.

Languages now supported by TubeSpy include:

  • English
  • Arabic
  • Chinese
  • Dutch
  • French
  • German
  • Italian
  • Japanese
  • Korean
  • Portuguese
  • Russian
  • Spanish

Here's a sample in Russian:

The app is still in beta, so be aware there may be some layout/formatting issues with the additional languages. In any case, please send us your comments, bugs, and feature requests.

Go to TubeSpy

JavaScript Jobs Site

Tagged:  

John Resig has just created JavaScript Ninja Jobs, a site dedicated to JavaScript Jobs. Currently, it's free to post and to apply for jobs on the site.

Some example jobs include:

  • Ajax Developer
  • User Experience Developer
  • Senior-level Web Developer
  • jQuery Plugin Developer
  • Rails Developer
  • Front-End Software Engineer

Check out these and other jobs at jobs.jsninja.com

There's also a Jobs RSS feed to keep you updated on the newest job postings.

Reading binary files using Ajax

Tagged:  

Over at Nagoon97’s Weblog they have an interesting post on reading a binary file in JavaScript. The post explains how the code was taken from another post and a comment that made the code work cross browser. With the trend of Ajax development going toward moving as much to the client as is prudent it is good to have a method for reading binary files should the use ever arise.

Below is an excerpt from the post.

So I put them all together in this BinFileReader function, which provides cross-browser support and helper methods to easily access the binary contents.

 

* BinFileReader: http://www.heypage.com/nagoon97/BinFileReader/BinFileReader.js

getFileSize() Return the file size
getFilePointer() Return the reading position
movePointerTo(iTo) Move the reading position to iTo.
movePointer(iDirection) Move the reading position in iDirection.
For all the following read functions,

- The reading position will move to the end of where the content is last read

- When iFrom is ommited, current reading position is used
readNumber(iNumBytes, iFrom) Read and return iNumBytes-byte number starting at iFrom.
readString(iNumChars, iFrom) Read and return iNumChars characters starting at iFrom.
readUnicodeString(iNumChars, iFrom) Read and return iNumChars unicoded characters starting at iFrom.

 

* Example:

var bmpFile = new BinFileReader(”image.bmp”);

bmpFile.movePointerTo(18);

var width = bmpFile.readNumber(4);

var height = bmpFile.readNumber(4);

 

* Demo:

http://www.heypage.com/nagoon97/BinFileReader/BinFileReader_demo.html

http://www.heypage.com/nagoon97/BinFileReader/MosaicBuilder_demo.html

You can read the full post here.

This script could be used to make some interesting applications, now if we could only write binary files to the system (I know that there would be a huge security hurdle to get pass). If you use this script then I would love to hear about your experience with it (as usual you can leave it in the comments or write a blog post about it using your free Ajaxonomy account).

Explore Dojo with Dojo Campus Feature Explorer

Dojo Campus has an interesting application called the Dojo Campus Feature Explorer. The application allows you to see examples of various features of the Dojo library and the HTML for each example. The application has an incredible amount of information.

You can go to the Dojo Campus Feature Explorere here.

I recommend this application to anybody that is wanting to learn more about using Dojo.

A Better Ajax Back Button - Part2

After a post that I wrote a few months ago on A Better Ajax Back Button, I received many comments. Many of the comments have asked for more information on the post and a working example.

In my previous post the code I used was done using JavaScript prototype objects. Because for some this is a bit more difficult to read I made this example as simple as possible to make it a bit easier to understand.

The below is the JavaScript portion of the code that is needed to accomplish the back button solution.

		function CheckForHash(){
			if(document.location.hash){
				var HashLocationName = document.location.hash;
				HashLocationName = HashLocationName.replace("#","");
				document.getElementById(HashLocationName).style.display='block';
				document.getElementById('Intructions').style.display='none';
				for(var a=0; a<5; a++){
					if(HashLocationName != ('Show' +(a+1))){
						document.getElementById('Show'+(a+1)).style.display='none';
					}
				}
			}else{
				document.getElementById('Intructions').style.display='block';
				for(var a=0; a<5; a++){
					document.getElementById('Show'+(a+1)).style.display='none';
				}
			}
		}
		function RenameAnchor(anchorid, anchorname){
			document.getElementById(anchorid).name = anchorname; //this renames the anchor
		}
		function RedirectLocation(anchorid, anchorname, HashName){
			RenameAnchor(anchorid, anchorname);
			document.location = HashName;
		}
		var HashCheckInterval = setInterval("CheckForHash()", 500);
		window.onload = CheckForHash;

In the above code you will notice that the function RedirectLocation calls the RenameAnchor function then sets the value of the hash (if you read the original article I go into more detail about what an anchor and hash are) in the URL. It is important that the RenameAnchor function is called before setting the hash value as it is important that an anchor with the same value as the hash exists before changing the value in order for the back button trick to work. The next important thing is that an interval is set to call the CheckForHash function (this interval could be whatever you want, but the smaller the number the more responsive the back button will be to the user) which checks the hash value and depending on the value will display a div (in your application you could have the function different, but I just wanted to keep it simple by showing and hiding div's).

Below is the HTML portion of the code.

	<a id='LocationAnchor' name=''></a>
	<div id='linkholder'>
		<a href='javascript:RedirectLocation("LocationAnchor", "Show1", "#Show1");'>Display Option 1</a><br />
		<a href='javascript:RedirectLocation("LocationAnchor", "Show2", "#Show2");'>Display Option 2</a><br />
		<a href='javascript:RedirectLocation("LocationAnchor", "Show3", "#Show3");'>Display Option 3</a><br />
		<a href='javascript:RedirectLocation("LocationAnchor", "Show4", "#Show4");'>Display Option 4</a><br />
		<a href='javascript:RedirectLocation("LocationAnchor", "Show5", "#Show5");'>Display Option 5</a>
	</div>
	<div id='Show1' style='display:none;'>
		1st Option
	</div>
	<div id='Show2' style='display:none;'>
		2nd Option
	</div>
	<div id='Show3' style='display:none;'>
		3rd Option
	</div>
	<div id='Show4' style='display:none;'>
		4th Option
	</div>
	<div id='Show5' style='display:none;'>
		5th Option
	</div>
	<div id='Intructions' style='display:block;'>
		Click on the above links to see different values, then use the back button to see your browsing history.
	</div>

In the above code there is an anchor tag that will be renamed in the JavaScript to trick the browser into thinking that the anchor exists. We then have all of the links set to call the RedirectLocation function in order to make sure that the hash and anchor values are set correctly. Finally there are a series of div tags that hold various content and will be displayed or hidden.

That is pretty much all there is to the example. You can view the sample here. Or you can download the code here.

I have tested the script without any issues on Firefox 2.0.0.13 and on Internet Explorer 7. It should work on Opera, Safari and earlier version of Internet Explorer and Firefox, but I have not had a chance to test on these browsers.

In my testing the code works with the back button, forward button and the refresh button. Plus pages where bookmarked correctly.

If you find a good use for this code I would love to hear about it (you can leave it in the comments or write a blog about it with your free Ajaxonomy account).

33 Most Beautiful JavaScript and Flash Galleries

v!valogo has put together a great list of JavaScript and Flash Gallery scripts. The list includes 33 scripts and is quite an impressive list.

Below is just a small sample of the Galleries.

AJAX Image Gallery powered by Slideflow

Lightweight Image Gallery with ThumbnailsDemo

Live Pipe PhotoFolderDemo

JaSDemo

JaS is a highly customizable JavaScript library for easily turning your images into a collection viewable as a slideshow, and with fading effects, if desired. It also supports automatic thumbnail creation and tagging of images, so the viewers can find the exact images they're looking for. You can use it any way you like in your own web site, and adapt it to your specific needs.

MooFlow

MooFlow is a Javascript based Gallery looks like Apple's iTunes or Finders CoverFlow.

You can see all 33 JavaScript and Flash Galleries here.

If you are looking for a cool way to display images on your site or application I definitely recommend checking out this list.

Syndicate content