A Comparison of 3 JavaScript Frameworks – Part 1 jQuery

Posted by admin on 2009/02/07 under JavaScript, MooTools, Prototype, jQuery | 4 Comments to Read

I’m a jQuery fan, I love the framework and for me its a joy to use. But I also love to learn new things, try other tools, in this instance other JavaScript Frameworks. In particular Prototype with Scriptaculous and MooTools. So I decided to compare the three. Not to try to determine which one is better, but to compare how to accomplish the same tasks with each framework.

I’ll be dividing this up into a 3 part series, to keep the posts from running too long. In part 1 I’ll look at the jQuery code, part 2 will be on Prototype/Scriptaculous and part 3 will be on MooTools.

To best be able to compare tasks, I set up three identically structured pages, one for each of the frameworks. I then set myself a list of tasks, and set about accomplishing those tasks with each framework. The tasks are all pretty simple, but serve as a good comparison on how to accomplish those tasks with each of the three.
Tasks

  1. Append text to an element when clicked
  2. Animate an element when another is clicked
  3. Highlight every other list element
  4. Append a form field’s value to an element

Like I said, pretty simple, but enough to give you an idea of how each framework handles things.

If you want to jump ahead a bit you can find the jQuery page here, the Prototype/Scriptaculous page here and the MooTools page here. (I’ll also provide links to the pages at the end of the post so that you don’t have to scroll all the way back up here to view them.) Simply view the page sources to compare the three.

The XHTML

The XHTML is pretty straight forward, consisting of some standard XHTML elements and some descriptive text.


jQuery Tests

Click the heading above! When you click the heading above, the blockquote below the ordered list will animate. Prototype/Scriptaculous seems to have a problem with setting the margin when animating, while jQuery seems to have a problem with setting the background color when animating. To see the results when using Prototype/Scriptaculous or MooTools. In addition, every other list item in both the ordered list and the unordered list should be highlighted with a yellow back ground, view source to see how this was accomplished.

Header Level 2

  1. View this page using Prototype/Scriptaculous
  2. View this page using MooTools
  3. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  4. Aliquam tincidunt mauris eu risus.
  5. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
This is the blockquote (<blockquote>) that should be animated by clicking the h1 (<h1>) at the top of the page. It should shrink in width to 400px, get a gray background (#CCCCCC), padding set to 25px and shift to the left by 125px (margin: 0px 0px 0px 125px;). jQuery doesn't support animating the background color.

Header Level 3

  • Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  • Aliquam tincidunt mauris eu risus.
  • Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
In the form below, the value of the first form input should be appended to the legend.
Test Form
#header h1 a { display: block; width: 300px; height: 80px; }

The stylesheet is shared by all three pages, helping to ensure that everything looks the same across the pages. The only difference between the three is, naturally, the script blocks. I chose to use the Google AJAX Libraries API to load the frameworks, as this makes things a bit quicker. If you’ve been to another site that uses these frameworks and the Google API, chances are that they are already cached by your browser and so won’t have to be downloaded.

What I want to do here is take a look at each task, one-by-one and compare how to it with the three frameworks. I don’t claim to be an expert in any of the frameworks, and there may be better ways to accomplish each task, if you know of a better way, let me know and I’ll gladly update the code.

The JavaScript

So on with the first task, append text to an element when clicked. After we look at the overall code, I’ll break each task down and go over how its implemented in each framework. Let’s get started, here’s the jQuery code:

jQuery(function($) {
	// Append ' - Clicked!' to an h1 when it is clicked
	// and animate the blockquote
	$('#clickable').click(function() {
		$(this).append(' - Clicked!');
		$('#quote').animate({
			marginLeft: '125px',
			backgroundColor: '#CCCCCC',
			width: '400px',
			padding: '25px'
		}, 1000, 'swing');
	});

	// Show the jQuery Version
	$('#version').append('jQuery Version: ' + $().jquery);

	// Highlight every other list item
	$('li:odd').addClass('highlight');

	// Append the value of the first input to the legend
	$('#test-form-legend').append(' - ' + $('#testInput1').val());

	/*** Twitter Search ***/
	// Capture the form submit
	$('#search-twitter').click(function(e) {
		$.ajax ({
			url: 'http://search.twitter.com/search.json?q=' + $('#twitter-search-query').val(),
			dataType: 'jsonp',
			success: function(data, textStatus) {
				$('#search-results').slideUp().empty();

				var html = '


';

				$('#search-results').append(html).slideDown();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.error(textStatus + ': ' + errorThrown);
			}
		});

		// Prevent the normal form submit process
		return false;
	});
});

Appending Text and Adding Classes

The first task is to append ‘ – Clicked!’ to the h1 when it is clicked. In jQuery we’ll do everything when the DOM is ready. There are several ways to accomplish this, but my preference is to use:

jQuery(function($) {
 
});

All of the code is contained within this block.

Now we can get down to details. We’ll start by taking a look at the things that happen without user interaction. If you looked at the demo pages you can see that I’ve displayed the version of the framework. Its a simple thing to do, though not well documented at least in jQuery.

$('#version').append('jQuery Version: ' + $().jquery);

In jQuery $() is a powerful function, it allows us to access any element in the DOM, tags, class, ids, etc. Here I’m using it to access the div with the ID of ‘version’, then we append the jQuery version to it.

You should also have noticed that every other list item is highlighted. I did this with this bit of code:

$('li:odd').addClass('highlight');

The selector $(’li:odd’) places every li on the page in an array, zero-indexed, and allows us to access the ones with an odd numered key. addClass(’highlight’) applies a CSS rule for the class highlight to those elements. Pretty straightforward.

The value of one of the form fields is appended to the legend as well.

$('#test-form-legend').append(' - ' + $('#testInput1').val());

We’ve already seen how we can select elements, but the val() we haven’t looked at yet. This function returns the value of any element it is chained to, in this case the form input with the ID of ‘testInput1′. That value is then passed to the append function which appends it and the dash to the legend.

That covers the things on our page that don’t require user interaction, so let’s move on to the ones that do.

User Interaction

If a user clicks on the h1 element two things happen. Text is appended to the h1 and the blockquote is animated. Nothing fancy, but it shows the basics of two things. Attaching events to an object and animating an object.

To attach a click event to the h1 I just chained the click() function to the h1 after I selected it.

$('#clickable').click(function() {

});

The click() function takes a single argument, a callback function, to run when the object it is chained to is clicked. This function can be defined elsewhere, or as an anonymous function, as I’ve done here.

$('#clickable').click(function() {
	$(this).append(' - Clicked!');
});

Again, we’ve seen the append() function before, but $(this) is new (no pun intended). $(this) is passed into our anonymous function and is the jQuery object returned by $(’#clickable’). So what I’m saying is, when the h1 is clicked append ‘ – Clicked!’ to the h1.

When the h1 is clicked, not only does it get appended to, but the blockquote gets animated as well. This is accomplished with the animate() function.

$('#clickable').click(function() {
    $(this).append(' - Clicked!');
    $('#quote').animate({
        marginLeft: '125px',
        backgroundColor: '#CCCCCC',
        width: '400px',
        padding: '25px'
    }, 1000, 'swing');
    });
});

animate() takes, at a minimum a list of CSS properties to animate. If you’ve looked at the demo page or tried this on your own, you’ve no doubt noticed that the background color didn’t get animated, this is because animate() only animates properties that take a number, width, height, margin, etc. and as a result colors won’t get animated.

The Bonus

If you’ve made it this far, and you remember the overall code we showed in the beginning, you’ve probably noticed that we didn’t cover or even mention a block of code that was there. This block of code allows us to use AJAX to search Twitter for keywords. In the interests of brevity I will cover this code in detail in part 4 of this series, I know at the beginning I said 3 parts, but that’s part of the bonus.

You are more than welcome to use this code in your own projects, though I would appreciate a link back :)

/*** Twitter Search ***/
// Capture the form submit
$('#search-twitter').click(function(e) {
	$.ajax ({
		url: 'http://search.twitter.com/search.json?q=' + $('#twitter-search-query').val(),
		dataType: 'jsonp',
		success: function(data, textStatus) {
			$('#search-results').slideUp().empty();

			var html = '


';

			$('#search-results').append(html).slideDown();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.error(textStatus + ': ' + errorThrown);
		}
	});

	// Prevent the normal form submit process
	return false;
});

I hope you’ve enjoyed this post as much as I’ve enjoyed writing it. Until next time.

  • Share/Bookmark
  • Lim Chee Aun said,

    Of all the three test pages, I notice that the blockquote is not showing a gray background, in the jQuery test page, on Firefox 3.

  • mdrisser said,

    @Lim Chee Aun jQuery’s animate() function only animates objects that take a numeric value (width, height, top, left, etc) and so won’t animate a background color. From the jQuery docs: “Only properties that take numeric values are supported (e.g. backgroundColor is not supported).” http://docs.jquery.com/Effects.....amsoptions

    Hopefully this is something that the jQuery Team will address in the future.

  • Lim Chee Aun said,

    @mdrisser oh, I didn’t notice that. Probably need the jQuery Color plugin then http://plugins.jquery.com/project/color

Add A Comment