I wrote this up a while ago, I don't even remember why, but thought some people might enjoy it.
"JavaScript, Ugh."
For many web developers, JavaScript is one of those subjects they'd rather avoid. Five years ago, the landscape of client-side scripting was pretty bleak. Browser inconsistencies, implementation bugs and numerous target platforms made developing client-side JavaScript a messy endeavor.
And then, much to the chagrin of those developers, "Web 2.0" happened. Overnight, every site on the internet began using AJAX, every feature request for a site involved something dynamic and client-side, and JavaScript development quickly became as important a skill as any server-side technology.
Enter the Libraries
As this trend continued, smart developers began longing for the level of abstraction found in most server-side environments. Just as a PHP developer could call mail() on nearly any platform and expect to have an email message sent, JavaScript developers craved this level of abstraction in their day to day work.
In response to this need, several sharp developers have responded with JavaScript libraries to fill this gap. These libraries seek to provide a uniform interface, across browser and operating system platforms, for the most common tasks that client-side scripting is called on to perform:
- DOM Manipulation (moving page elements around, hiding and showing objects)
- AJAX and other flavors of client-server interaction that avoid a page refresh
- Animation
- Rich Interfaces (drag and drop, windowing, tabs, events)
- Form manipulation
Each of the popular libraries attempt to provide some or all of these capabilities, packaged in their own API.
On to jQuery
This article focuses on one of theses libraries, jQuery. jQuery design is focused on maintaining a small footprint, cross-browser compliance, and reducing the amount of code which must be written for applications. It provides abstractions for AJAX, DOM manipulation, event handling and animated effects.
Developing with jQuery depends on two basic concepts, CSS selectors and method chaining.
In most vanilla JavaScript code (which does not make use of a library), you will find code like this:
function toggle_element( element_id ) {
var element = document.getElementById( element_id );
if ( !element ) {
return false;
}
var display = element.style.display;
if ( !display || display == 'block' ) {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
return true;
}
window.onload = function () {
var toggler = document.getElementById( 'toggle_help' );
if ( toggler ) {
toggler.onclick = function () { toggle_element( 'help' ) }
}
}
The basic idea here, is that when the page is done loading, during the window.onload event, we find the toggle_help element and attach an onclick event to it. When that element is clicked, we find the DOM element with an id of "help", examine its current display state (the CSS attribute which controls how it is presented in the flow of the page), determine if it is currently hidden or not, and toggle its display state.
The same code, implemented with jQuery looks something like this:
$(document).ready( function () {
$('#toggle_help').click( function () { $('#help').toggle(); });
});
As you can see, the code is significantly shorter. Admittedly, to try and compare based on the 22 versus three line count is a bit silly, as one could easily add or subtracts line from either implementation. I think it is clear, though, which version is simpler. jQuery strives to provide an appopriate level of abstraction, simplifying the developer's task, but not obscuring it behind a heavy API.
An important example of the abstraction jQuery provides is the $(document).ready() construct. This serves as an enhanced version of window.onload. The primary enhancement is that it acts in a cross-platform waym firing as soon as the DOM of the page is ready for manipulation. This is in contrast to window.onload which can be delayed indefinitely if objects on the page load slowly or improperly (images, iframes, scripts, etc.)
CSS Selectors
As shown in the previous example, one core features of jQuery is the use of CSS selectors to find elements within the page. By now, I imagine that most web developers have had exposure to at least basic CSS, which is all you'll generally need in order to develop very useful jQuery code. The selector engine in jQuery implements CSS2 and CSS3 selectors, as well as adding a few useful extras. The following examples, outline various selectors.
Very concise selectors and code fragments are provided by the use of the $ symbol. This is not a reserved character in JavaScript, and is used in jQuery as an alias for the main jQuery object. This will be seen throughout the examples.
To start, here's the page we'll work against for these selector examples:
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div id="header">
<h1>Test Page</h1>
</div>
<div class="instructions">
<ul>
<li>Read Page</li>
<li>Follow Examples</li>
</ul>
</div>
<div id="mainform">
<form>
<span class="instructions">
Fill out this form.
</span>
<input type="text" name="first_name" />
<select name="gender">
<option>Male</option>
<option>Female</option>
</select>
</form>
</div>
</body>
</html>
A simple example, find the header and slide it out of view. The # character, in front of a name is used to find an element by its id attribute. An id should be unique in a pages structure. slideUp() is an animation method which decreases the height of an element over time, until it is hidden.
$('#header').slideUp('slow');
Find the title heading of the page, and change its color. In the selector, nested elements are found by simply following one selector with another.
$('#header h1').css('color', 'red');
Remove the second element of a list. The :nth-child() selector is provided by jQuery to facilitate this. remove() takes matched elements out of the DOM.
$('#instructions ul li:nth-child(2)').remove()
Where the CSS selector concept becomes very powerful, is when you want to operate on groups of items. All methods of the jQuery object will operate across all the elements that match a given selector.
Here, we'll find all the instructions and add a class to them. addClass() is a method which adds a CSS class to the matched elements, useful to quickly change items to match a set style. An important note, regarding addClass() is that an HTML element may have more than once class, even though this is not seen very often. To match all elements which have a given class, the classname is started with a period.
$('.instructions').addClass('warning');
These are some rather simple examples, but they touch on the main principles you'll use when creating selectors for use with jQuery. Details on all the selectors available are provided in the jQuery Docs.
Method Chaining and 'this'
One possible disadvantage to using CSS selectors, as outlined above, is that very complex selectors can become a performance bottleneck. They can also result in your code being cluttered with the same selector over and over, as you repeatedly manipulate the same elements. Two facilities help alleviate these issues.
Method Chaining
All methods of the jQuery object return themselves. This will be a familiar concept to many object-oriented programmers, but can look a bit foreign to others. The basic idea being that you need only perform a given selection operation once, and then you perform all necessary operations on that set of results.
$('.intructions').fadeIn('fast')
.css('border', '1px solid red')
.addClass('warning');
In this example, we find all the instructions. We cause them to appear, give them a red border and add the warning class. (Apparently, we really, really want our instructions followed) It is important to remember that this is equivalent to the following:
$('.intructions').fadeIn('fast');
$('.intructions').css('border', '1px solid red');
$('.intructions').addClass('warning');
Chaining methods in this manner allows for more concise code and snappier performance, as the selection operation need only be performed once.
'this'
Another facility provided is the definition of this inside each jQuery method context to reflect the current element being operated on. This becomes important with more advanced concepts, as many of them rely of providing callback functions which are executed in the context of each element matched by the selector.
In this example, we find every element with the class "click_to_hide" and then attach an onclick event to it.
$('.click_to_hide').click( function () {
$(this).hide();
});
As you can see, we are creating an anonymous function for each element, and when the element is clicked, the element will be hidden. In this instance, we wrap this in the jQuery/$ method so we have access to the hide() method. Before wrapping, this is simply a DOM Element.
AJAX and Event Handling
Two final topics I'll touch on are AJAX and event handling. jQuery provides nice abstractions for both of these, which are likely to prevent numerous bugs and speed development.
AJAX
The must-have feature for modern web sites, AJAX, is greatly simplified when using the jQuery library. Without using a library, you would be writing complex code to first instantiate a browser-specific XmlHttpRequest object, then initiating a request and writing a callback function to be triggered.
With jQuery, for the most common cases of AJAX usage, you can accomplish this with one simple line:
// Grab the content of url and inject it into #div_to_load_in
$('#div_to_load_in').load(url);
For a more complex case, where you want to manipulate or act on the result, you'll need to add a bit more code.
var url = '/update_status.php';
$.get(url, {status: $('#status_field').val(}), function (data) {
if ( data == 'OK' ) {
alert('Status Updated');
}
else {
alert('Sorry, Status Update Failed. (' + data + ')');
}
});
Here we're assuming the existence of a server-side script, "update_status.php", which takes a "status" GET parameter and returns either "OK" or an error message. In this example, I also utilized the val() jQuery method which abstracts the process of obtaining the value from any form element. This includes finding the value attribute of the selected option in a <select> tag, value of a text field, or status of a checkbox.
Event Handling
Event handling in jQuery involves jQuery object methods which bind functions to events. All of these binding methods are chainable, as with the previous examples. Many of the browser-native events are simplified or enhanced, to make the script writer's life easier.
An example of this is hover() which allows you to bind a function to the movement of the mouse cursor in and out of an element. Here we add a faux caret to elements of a list as we hover over them, add a 'selected' class, and then remove these decorations when the user's mouse moves on.
$('li').hover(
function () { $(this).prepend('<span>></span>').addClass('selected'); },
function () { $(this).removeClass('selected').find('span:first').remove(); }
);
In this example, we see use of this, method chaining, and find() which allows using selectors to dig down inside of an element.
Further Reading
Hopefully, you now have a feeling for what jQuery can do for your code. This was simply the 10,000 foot introductory fly-by... jQuery packs a sizeable array of methods and functionality into its 14kb size, and it takes a while to familiarize yourself with most of them. To continue you exploration, these sites may be of use:
Show Related Articles

jminkler :: Mon, 14 Jul 2008 00:45
jQuery ... ehhh ... its like spam ... :)
Nicibx24 :: Tue, 05 Jan 2010 04:44
The quantities of essay writers write the custom essay about this good topic. Thence, its really good possibility to <a href="http://www.gogetessays.com">buy an essay</a> or buy term paper about this good topic.
Travel Guide :: Fri, 05 Feb 2010 19:30
Being a beginning web developer I'm not experienced in serious JavaScript coding. Just the basics for what I need so far. I decided a few weeks ago to get more into JS, mainly for normal web site- and CMS behaviour.. but this article convinced me. http://www.datelot.com
Matrimony :: Fri, 05 Feb 2010 19:31
Iam a beginner of JQuery. I never expected the things that can be achiveable with Jquery. We can reduced lots of client side scripting with Jquery. thanks
eskort bayan :: Tue, 23 Feb 2010 09:02
Good work! Your post/article is an excellent example of why I keep comming back to read your excellent quality content that is forever updated. Thank you!
thesis :: Sat, 27 Feb 2010 23:18
You are very master and your outcome just about this good topic supposes to be hottest. Should you continue your work? We will buy the thesis mba or <a href="http://www.exclusivethesis.com">dissertation</a> from you.
buy custom essays :: Thu, 04 Mar 2010 00:13
If you are confused and dont really know the way to create the <a href="http://www.supremeessays.com/customized-essay.html">customized essay</a>, you will have a chance to <a href="http://www.supremeessays.com/buy-paper.html">buy paper</a> in the masters writing service. That can save time.
Buy essay :: Thu, 11 Mar 2010 14:59
Some people find some facts close to this good post from the different sources. Moreover, I will propose to <a href="http://www.essayslab.com">buy essays</a> selecting the custom writing services. Thus, people very often order custom papers.
King27Latisha :: Fri, 09 Apr 2010 18:44
Would you like to get <a href="http://www.prime-resume.com">professional resume service</a>, which conform the range of research you expect?. You can trust our resume writers, as you count on yourself. Thanks because this is the useful stuff
urbanclothing4u :: Fri, 07 May 2010 15:57
buy <a href="http://www.urbanclothing4u.com/wholesale/Coogi-125_p1.html">coogi wholesale </a>,<a href="http://www.urbanclothing4u.com/wholesale/Prada-127_p1.html">Prada Sneakers wholesale </a>,<a href="http://www.urbanclothing4u.com/wholesale/Gucci-128_p1.html">Gucci discount clothing </a>,<a href="http://www.urbanclothing4u.com/wholesale/Ed-Hardy-123_p1.html">Cheap Ed Hardy China outlet </a>, <a href="http://www.urbanclothing4u.com/wholesale/Louis-Vuitton-126_p1.html">Louis vuitton </a> high top shoes,Flip Flop Louis Vuitton wholesale,discount true religion jeans! Huge selection of your Favorites Low Price Guarantee & Fast Shipping!<br /> Shop for high quality <a href="http://www.urbanclothing4u.com/wholesale/Air-Jordans-121_p1.html">wholesale Air Jordan </a> From China,Wholesale Nike Sneakers on urbanclothing4u.com and get worldwide delivery.</p> <p>More products following:<br /> <a href="http://www.urbanclothing4u.com" title="http://www.urbanclothing4u.com">http://www.urbanclothing4u.com</a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Nike-Sneakers-120_p1.html">Nike Sneakers </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Air-Jordans-121_p1.html">Air Jordans </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/MBT-122_p1.html">MBT </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Ed-Hardy-123_p1.html">Ed Hardy </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Christian-Audigier-124_p1.html">Christian Audigier </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Louis-Vuitton-126_p1.html">Louis Vuitton </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Coogi-125_p1.html">Coogi </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Prada-127_p1.html">Prada </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Gucci-128_p1.html">Gucci </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Chanel-129_p1.html">Chanel </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Timberland-130_p1.html">Timberland </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/UGG-131_p1.html">UGG </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Puma-132_p1.html">Puma </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Supra-133_p1.html">Supra </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Mauri-134_p1.html">Mauri </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Coach-135_p1.html">Coach </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Crystal-Rock-136_p1.html">Crystal Rock </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Juicy-Couture-137_p1.html">Juicy Couture </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Affliction-138_p1.html">Affliction </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/True-Religion-139_p1.html">True Religion </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Miu-Miu-140_p1.html">Miu Miu </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Chloe-141_p1.html">Chloe </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Lacoste-142_p1.html">Lacoste </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Ralph-Lauren-143_p1.html">Ralph Lauren </a><br /> <a href="http://www.urbanclothing4u.com/wholesale/Dolce&Gabbana-144_p1.html">Dolce&Gabbana </a></p>
faxless payday loans :: Sun, 23 May 2010 11:47
Would you like to get
simulateur de credit auto :: Mon, 24 May 2010 17:42
Great minimalist designs. I'm a firm believer in the k.i.s.s. design method. After all, most of the biggest sites on the web use minimalistic designs, like Google, eBay, Amazon, etc. As long as it's a good user interface, minimalist design is a great choice.
Teeth Whitening :: Thu, 27 May 2010 11:43
Being a beginning web developer I'm not experienced in serious JavaScript coding!
best payday loans :: Sat, 05 Jun 2010 17:41
I'm not experienced in serious JavaScript coding!
bulk natural peanut butter :: Mon, 07 Jun 2010 07:34
I found this is an informative and interesting post so i think so it is very useful and knowledgeable. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing ability has inspired me. Really the article is spreading its wings rapidly...
essay topics :: Tue, 15 Jun 2010 08:08
thanks!!!very nice code!it helps me a lot!!!
lacewigs :: Thu, 17 Jun 2010 07:52
I'm not experienced in serious JavaScript coding!
registry cleaners :: Fri, 18 Jun 2010 07:50
nice story, your experince very inspiring me
essays :: Fri, 18 Jun 2010 10:59
buy <a href="http://www.bestessays.com">essays</a>, it will help you in learning and save your time
tinggi badan :: Sat, 19 Jun 2010 07:53
As this trend continued, smart developers began longing for the level of abstraction found in most server-side environments. Just as a PHP developer could call mail() on nearly any platform and expect to have an email message sent, JavaScript developers craved this level of abstraction in their day to day work.
eyelash extensions :: Tue, 22 Jun 2010 09:30
JavaScript developers craved this level of abstraction in their day to day work.
buy ssay online :: Thu, 01 Jul 2010 08:25
Begin your term paper writing and do not have knowledge the proper way to complete it? You not have to be worried, simply buy custom essays Online and be sure that your custom essay writing are performed by experienced essay writers.
Info Pool :: Tue, 13 Jul 2010 06:50
Thanks for the nice post. Your post just made my day. It was very useful for me. Keep sharing such ideas in the future as well.
online degree :: Wed, 14 Jul 2010 05:52
Great help for making intro part of JQuery
Mesothelioma :: Thu, 15 Jul 2010 11:02
Jquery language is too much help, Nice help !!
Mortgage Refinance :: Thu, 22 Jul 2010 09:43
I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.