Advertisement
  1. Code
  2. Explanatory

Why Bother With jQuery? A Guide for (Former) Flash Developers

Scroll to top
Read Time: 10 min

If you, like many Flash developers, are looking into using HTML5 for your web apps, you'll almost certainly have come across jQuery. It's a very popular JavaScript library, used by a large percentage of the most visited websites - but what's all the fuss about, and should you use it?


Background

If you know AS3, you basically know a lot of JavaScript already; the two languages are very similar. So it's tempting to just jump straight in and code - but there are a few important concepts you need to understand first. One of these is the idea of the DOM.

When you load a webpage, your browser turns flat HTML into a tree-like structure of JavaScript objects called the DOM (Document Object Model). The JavaScript DOM, then, is very similar to the ActionScript Display List; and if you're a Flex developer, you'll be able to see the similarities between MXML and HTML.

In Flash, we can access specific display objects by navigating to them through the display list, like stage.getChildAt(3).getChildAt(0), but this is pretty ridiculous. Instead, we're more likely to give display objects instance names (through the Flash IDE), or store references to them in variables, arrays, or object properties, like dialogBox.okButton = new SimpleButton().

In JavaScript, we could construct our DOM entirely through JS and then tell the browser to render it, but this is an unusual approach; we're much more likely to define the DOM via HTML, perhaps with a little JS augmentation. So, JavaScript has various different methods for accessing elements of the DOM.

The simplest of these is document.getElementById(). If we have an HTML document defined like this:

1
2
<!DOCTYPE html>
3
<html>
4
<head>
5
<title>Example Page</title>
6
</head>
7
<body>
8
<div>
9
<span id="example">
10
<p>Here's some example text.</p>
11
</span>
12
</div>
13
</body>
14
</html>

...then document.getElementById("example") will get us the highlighted span object from the DOM. We could then add a second p tag like so:

1
2
var newPara = document.createElement("p");
3
var newTextNode = document.createTextNode("More example text that we created on the fly.");
4
newPara.appendChild(newTextNode);
5
document.getElementById("example").appendChild(newPara);

This would update the DOM, making it equivalent to what would have been created if the original HTML was as follows:

1
2
<!DOCTYPE html>
3
<html>
4
<head>
5
<title>Example Page</title>
6
</head>
7
<body>
8
<div>
9
<span id="example">
10
<p>Here's some example text.</p>
11
<p>More example text that we created on the fly.</p>
12
</span>
13
</div>
14
</body>
15
</html>

What if you wanted to then access the two p elements? We can't access them directly with document.getElementById(), since they have no ID, but we can use document.getElementsByTagName("p") to obtain an array containing both of them.

And if we'd had another span, like this:

1
2
<div>
3
<span id="example1">
4
<p>Here's some example text.</p>
5
<p>More example text that we created on the fly.</p>
6
</span>
7
<span id="example2">
8
<p>A second span.</p>
9
<p>We don't care about these paragraphs.</p>
10
</span>
11
</div>

...and we only wanted to obtain the first two p tags, we could call document.getElementById("example1").getElementsByTagName("p") just to retrieve those two - all these DOM functions work at any level in the tree structure, just like how every Flash DisplayObjectContainer has methods like getChildAt().

This is simple enough to understand, but there are problems. The first, you may not be surprised to hear, concerns Internet Explorer.


Cross-Browser Compatibility

Impressive Webs has a great outline of Internet Explorer's getElementById() problem. Essentially, if you have an HTML element like this:

1
2
<span name="exampleName"></span>

...then, in most browsers, document.getElementById("exampleName") will not give you the span in question, but in IE7, it will. (Other browsers could use document.getElementsByName("exampleName")[0] to return this particular span.)

This means that, to be consistent across browsers (and assuming we can't change the HTML), we'll need to write code like this:

1
2
var theSpan;
3
if (usingIE) {    //I won't explain how to detect the browser here

4
	var temp = document.getElementById("exampleId");
5
	//this might have returned an element with a name of "exampleId", so we must check:

6
	if (temp.getAttribute("id") == "exampleId") {
7
		theSpan = temp;
8
	}
9
}
10
else {
11
	theSpan = document.getElementById("exampleId");
12
}

More generally, we could wrap that up into a re-usable function:

1
2
function getElById(id) {
3
	if (usingIE) {
4
		var temp = document.getElementById(id);
5
		if (temp.getAttribute("id") == id) {
6
			return temp;
7
		}
8
	}
9
	else {
10
		theSpan = document.getElementById(id);
11
	}
12
}

Great! But, unfortunately, there are so many of these irritating little differences; it will probably surprise you, if you're coming from a straight-Flash background, where "compatibility issue" generally means that the Flash Player is a little slow on certain platforms.

jQuery solves this. It papers over the cracks between different browsers with its own set of functions, so if the user's browser is at least as new as IE6, your code can have a consistent interface.

That's not the only way that jQuery makes JavaScript simpler...


Easy Syntax

Let's go back to this snippet of HTML, and assume we want to retrieve the highlighted p elements from the DOM:

1
2
<div>
3
<span id="example1">
4
<p>Here's some example text.</p>
5
<p>More example text that we created on the fly.</p>
6
</span>
7
<span id="example2">
8
<p>A second span.</p>
9
<p>We don't care about these paragraphs.</p>
10
</span>
11
</div>

With jQuery, we can just write:

1
2
jQuery("#example1 p")

That's all we need! #example1 says "get the element with an ID of example1" and p says "get all the p elements that are children of that element". It returns a "jQuery object", which is a JavaScript object that contains the two p elements themselves from the JS DOM, plus a few extra properties and methods specific to jQuery.

We can make it even shorter still, by replacing jQuery with $ - there's no mystery here; $ is just a short variable name. Compare it to native JavaScript code:

1
2
//regular JS, without cross-browser compatibility:

3
document.getElementById("example1").getElementsByTagName("p")
4
5
//jQuery, with cross-browser compatibility built in:

6
$("#example1 p")

It's not just shorter, it's consistent with CSS, which makes it easy to pick up. We could use the exact same selector as inside our jQuery() call to style these specific paragraphs in a CSS stylesheet:

1
2
#example1 p { color: red }

That's just a very simple example; I'm not going to go into detail, but I'm sure you can see the benefit of being able to use the same selectors in both CSS and jQuery.

More Than Just Selection

I mentioned that the jQuery objects returned by a $() call had additional methods and properties. These give you an easy syntax for writing other common pieces of code.

For example, we could add a mouse click event listener and handler function to both of those p elements like so:

1
2
$("#example1 p").click(function() {
3
	alert("You clicked a paragraph!");
4
});

Or, you could make them all invisible:

1
2
$("#example1 p").hide();

Or, you could run some more general JavaScript on them:

1
2
var allText = "";
3
$("#example1 p").each(function() {
4
	allText += $(this).text();
5
});

In each case, jQuery provides a simple, short, consistent way of writing. It means it's faster to get code from your head to the browser - and not just because it requires fewer characters.


Tweens and Transitions

Since Flash has its roots in animation, we're used to it having plenty of tweening capabilities built in - both in the Flash IDE and in the Tween class, not to mention the various tweening libraries available.

JavaScript is different; animation is not an intrinsic part of the platform. But little tweens and transitions are expected parts of the user interaction of modern web app: if I add a new comment on a thread, it slides into place; if I remove an item from my shopping basket, it flashes red and disappears. Without these, apps look unpolished.

jQuery adds these little transitions.

For example, let's say we want to make either of the aforementioned paragraphs fade out when they're clicked. Easy:

1
2
$("#example1 p").click(function() {
3
	$(this).fadeOut();
4
});

Nothing to it! And you can pass a duration and callback to the fadeOut() function, if you don't like the defaults.

For something a little more powerful, we can use the animate() method. This is essentially the equivalent of a tween; pass it a set of CSS properties and values to animate towards, a duration, a type of easing, and a callback, and it takes care of it all for you.

It's not exactly Greensock, but it's far more convenient than writing these effects from scratch, and ideal for web app interfaces.

Speaking of which...


UI Widgets

HTML has a few UI components built in, of course: buttons, text fields, and so on. HTML5 defines a few new ones, like a pop-up calendar picker and color picket (though these are currently only supported in Opera).

But these aren't enough, on their own, to make up a full, modern web app interface. There's nothing to handle tabs within a page, or a progress bar, or even a simple dialog window (outside of alert() and prompt()).

jQuery UI, an optional library build on top of jQuery, adds these extra widgets, with methods and events that are consistent with the usual jQuery syntax. Think of it as a JavaScript equivalent to Keith Peters' AS3 MinimalComps. The demo page shows it off better than I can explain it.

Every widget can support custom themes, so you can create a single skin that fits your site and apply it to every component, making it possible to modify their appearance all at once. Again: consistency! Plus, you can apply UI-related effects to other elements; make it possible for the user to drag or resize a DOM element, or click and drag a box around a group of elements to select them for submission.


Other Reasons jQuery is So Popular

The cross-browser compatibility, easy syntax, tween capabilities, and UI elements are the main benefits of jQuery over plain JS in my eyes. There are other reasons to like it, though:

  • It's widely-used, and has been around for six years: it's not some flash-in-the-pan "new hotness" that's still unproven and might just die off in a few months. You can trust that it'll be around for a while.
  • There's a big community surrounding it: this means there are plenty of tutorials and books and forums and people to learn from; you're not going to be fumbling around in the dark.
  • The documentation is excellent: seriously, take a look; it's very clean and full of examples and demos
    • There are even alternative sets of docs with different interfaces, if that's what you require (another example of the great community)
  • It's open source: the community can add to it, and you can hack on it and learn from it
    • Paul Irish has two videos breaking down what he learned from just running through the source

So why wouldn't you use jQuery? As with most technology choices, it's a question of making sure you're using the right tool for the job. If you have a simple DOM structure, or don't require fancy animations and transitions, or are mainly using the canvas to render your interface, rather than widgets, jQuery probably isn't necessary.

If you're already using one or more JavaScript libraries - Dojo, MooTools, YUI, etc. - you may well find that you don't need jQuery's functionality on top of what they offer. But my goal in this article is not to try to sell you on any particular library above any other.

I hope this article has helped to explain just what the big deal is about jQuery, particularly if you're coming from the world of AS3 and Flash. If you'd like to learn it, check out the jQuery tag over on Nettuts+ - jQuery for Absolute Beginners is a good place to start.

Let me know if you've any questions!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.