With the ever increasing number of websites and an overall surge of web professionals trying to make the Web a more beautiful and usable place, JavaScript has become fairly popular amongst web designers and developers in an attempt to overcome HTML and CSS shortcomings.
But, as we all know, JavaScript is a rather obtrusive language. It often happens to mess things up and worsen what before was good markup if we don't pay close attention to using unobtrusive JavaScript solutions. These are the reasons why web designers (and web professionals in general) avoid plain JavaScript like a plague and limit its usage to short and simple parts of the coding process.
Instead, jQuery has been designed with the aim of making it easier to navigate a document, select Document Object Model(DOM) elements, handle events, develop AJAX applications, and eventually smooth out any browser differences.
In this chapter, we will cover the following:
jQuery background
A jQuery introduction
How jQuery works
Extending jQuery using plugins
jQuery plugin basics
A reading material reference
Short after being officially presented by John Resig at BarCamp NYC in January 2006, jQuery, though still "new", spread rather quickly. It has become, as of today, the most used JavaScript library and is in use at 20 percent of the 10,000 biggest websites, including Google, Digg, and WordPress.
The reason why jQuery was created is to be found in the lack of a JavaScript library providing its users with a simple and easy-to-use syntax. In fact, at the time of its announcement, jQuery was aiming to improve and simplify the use of selectors in JavaScript a topic much overlooked by libraries such as Behaviour.
The library then rapidly gained community interest and, shortly after the first plugin had been developed, AJAX support and some new effects were added. Less than one year later, the first sponsored developer joined the team and, as of now, four years later, companies such as Nokia and Microsoft are actively supporting the open source library.
Its success, so huge and originating a fast growing movement, which has undoubtedly contributed to promoting the library, has definitely helped jQuery to constantly improve the quality of both its features and code. This has made it more and more popular over time, especially amongst ASP.NET developers, as a 2009 survey points out (http://codeclimber.net.nz/archive/2009/06/22/ajax-survey-2009-jquery-and-ms-ajax-are-almost-tied.aspx).
The code, free and dual licensed under the MIT License and the GNU General Public License (GPL) Version 2, proves its suitability to the purpose by being extremely lightweight and cross-browser, supporting a variety of web applications and taking relatively little time to execute.
Indeed, jQuery provides a simple and fast way to manipulate web pages, emphasizing the interaction between JavaScript and HTML. Even a few lines of code can make the User Interface (UI) more logical and way nicer to look at.
At first glance, we might think jQuery is only a different way to write JavaScript. However, after spending some time dealing with documentation or examples, we realize it's much more than a mere framework. It actually has features that make it easier and extremely straightforward to handle DOM elements (traversal, modification, and elements selection), deal with events (through specific calls), manipulate CSS, and create any type of effect and animation (sliding, fading, or combined effects).
Moreover, one of the main, big benefits of using jQuery over plain JavaScript is that the former hides the differences between browsers, at least to some level, relieving us of the onerous task of differentiating the code depending on the user agent.
Ultimately, it provides easy methods to access AJAX functionalities and extend the library itself through the use of plugins, which is the most powerful and useful way to interact with the jQuery API.
We're going to create a simple script to check if everything is set up correctly and is working properly.
1. Load the jQuery library; modify the
src
attribute of the<script>
element to point to the path of your jQuery file.2. Write some sample code inside the "document ready" event statement, to display a pop up message, as follows:
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf- 8" /> <title>jQuery test</title> <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { // runs once page is loaded and ready to be manipulated alert("Hello world!"); }); </script> </head> <body> <center><h1>jQuery test</h1></center> </body> </html>
3. Open the page in your web browser of choice and check if everything is alright.
There's no need to spend time talking about stuff like loading JavaScript libraries or displaying pop ups. Instead, it would make a good point to explain why, contrary to what most JavaScript programmers will do instinctively, we avoid adding code to our program once the window.onload
event strikes—right after the page is loaded.
However, the JavaScript code isn't actually run until all images are finished downloading, (which could last for quite a lot of time). Instead, jQuery's "document ready" event checks the document and only waits until it's ready to be manipulated, leaving images and other media to load at their own pace.
Callbacks are functions that are passed as an argument to another function and are to be executed at the appropriate time within the processing of the code (for example, when a click event happens or when an AJAX update is ready to be sent).
1. Inside the "document ready" statement, write these two functions with callback functions included:
$('#one').click(function() { $(this).hide(1000, function() { alert("hidden - callback function with one argument"); }); }); $('#two').click(function() { $(this).hide(1000, myCallbackFunction); }); function myCallbackFunction() { alert("hidden - callback function with no arguments"); }
2. Make sure you have two elements having IDs
one
andtwo
respectively.3. Point the web browser to this page to check the work done.
It's important to notice that, though the final result is the same, in this case, there is difference in the way callbacks are to be handled depending on them having (or not having) arguments:
If the callbacks don't require arguments, writing the function name (not as a string, nor with any parenthesis) is enough.
If the callbacks do have arguments to be passed along, we must register an anonymous function as the callback function and then execute the actual callback taking any number of arguments.
Another interesting point to understand is, in fact, what anonymous functions are and how they behave.
Following the previous example, we may notice we have bound the click
event directly to a structure in which we defined a function. This is what is called an anonymous function. It has no name and can be defined on the spot, resulting in a useful replacement for a function that we might use only once (and that would be a waste of time to define) and then call in two different places.
Apart from offering a simple, yet effective, way of managing documents, elements, and various scripts, jQuery also offers a mechanism for adding methods and extra functionalities to the core module.
Thanks to this mechanism, we are also allowed to create new portions of code and add them to our application everytime we need them. It results in a reusable resource that we don't need to rewrite in our next page or project.
Additional methods and functions created making use of this structure are then bundled as plugins. These can be subsequently used (and/or included) in new jQuery scripts, developed by the plugin authors themselves and by other people as well (if the code is released in some way thus made publicly available for download and use).
The extremely easy-to-use Application Programming Interface (API) jQuery is built on (evidently developed without forgetting the very beginner programmers out there, and the immediate syntax jQuery made us all used to), combined with a bit of will, makes jQuery plugin development not too harsh to regular script coders with a minimum of experience in the field, as well as to those new to either plugin writing or jQuery internal mechanisms.
Of course, writing simple plugins is fairly easy, whereas a more complex plugin requires a more advanced programming background and a certain proficiency with both JavaScript and jQuery.
Also, it's important to know that most of the methods and functions jQuery is packaged with were written by taking advantage of the jQuery plugin construct itself, thereby pushing towards steady and frequent improvements of this complex plugin architecture.
The question "So, what's all this about?" is likely to come naturally now.
In fact, this "plugin thing" may sound a little strange to newcomers, if they're not used to dealing with languages or frameworks that allow for such extension of features and options.
To dissipate even the slightest doubt, we're going to understand what plugins are and why they matter. Most importantly, we will see how is it possible to bring to light our own creation, starting from scratch and eventually shaping our original idea into a more concrete, working jQuery plugin.
Plugins are coded by making use of the jQuery API functions and methods, which are really handy on many occasions. However, plain JavaScript often happens to be used heavily, since, after all, it's the language jQuery is written in.
For those already familiar with jQuery syntax, methods, and features (everybody should be, when considering writing a plugin), flipping through the pages of any jQuery-related book is enough. However, if an inexperienced jQuery developer is reading this (even though they usually jump straight to some random code, so they're more likely to never see this part anyway), they'd better stop for a while and read some beginners' guide to jQuery programming first.
Code generated using the jQuery built-in tools and eventually packaged into a plugin, must then be included in the web page it's intended to work in, without forgetting that it requires a compatible version of jQuery to run properly. More generally, in fact, plugins are extra parts, not expected nor supported in any way by jQuery developers. These extra parts are attached to the main functions and add in new user-generated functionalities working on top of the core methods, functions, and options explicitly provided by the jQuery library for third-party use.
It is true that plugins, especially the well known ones, are normally supported by their authors. The authors are, usually, open to suggestions and feedback, and are constantly doing their best to make their work compatible and working flawlessly with the latest release of jQuery.
Thinking of plugin development as a wild-goose chase is obviously overplaying it. Some old wise man would probably say impossible is nothing, and he couldn't be more right. If each of these resources, all of this documentation, and these tools are at hand, authoring a plugin is a trifle requiring some special effort at the beginning along with a good knowledge of the basis.
Printed books are, even in our extremely digitalized era, one of the best sources to learn from. Also, they come handy whenever we have to look something up and haven't the possibility to switch to another window or just need to check something up—the book is there, right next to our keyboard.
By Jonathan Chaffer and Karl Swedberg—Packt Publishing, 2009
Book page: http://www.packtpub.com/learning-jquery-1.3/book
TOC: http://www.packtpub.com/article/learning-jquery-1.3-table-ofcontents
Note
"Revised and updated for version 1.3 of jQuery, this book teaches you the basics of jQuery for adding interactions and animations to your pages. Even if previous attempts at writing JavaScript have left you baffled, this book will guide you past the pitfalls associated with AJAX, events, effects, and advanced JavaScript language features."
By Jonathan Chaffer and Karl Swedberg Packt Publishing, 2010
Book page: http://www.packtpub.com/jquery-1-4-reference-guide/book
TOC: http://www.packtpub.com/jquery-1-4-reference-guide/book
Note
"Revised and updated for version 1.4 of jQuery, this book offers an organized menu of every jQuery method, function, and selector. Each method and function is introduced with a summary of its syntax and a list of its parameters and return value, followed by a discussion, with examples where applicable, to assist in getting the most out of jQuery and avoiding the pitfalls commonly associated with JavaScript and other client-side languages."
Beside printed paper resources, some online papers are often of great help when we are in need of some quick reference or other people's opinion as well. Here are some of the most useful and well-known pages we'll become familiar with.
There are many, many resources on this site. Have a look through the archives and search for jQuery-related tutorials to get overwhelmed by articles upon articles.
They also have a very well made video series called jQuery for absolute beginners—worth watching.
http://net.tutsplus.com/articles/web-roundups/jquery-for-absolute-beginners-video-series/ (jQuery video tutorials for beginners)
http://net.tutsplus.com/tutorials/javascript-ajax/15-resources-to-get-you-started-with-jquery-from-scratch/ (list of interesting links to get you started)
The following are some useful and practical references. These contain API references with detailed description and some sample code. Everybody should try some of these and pick the one that is most helpful to them.
There are many people out there happy to help. Asking in the following forums might be useful to get different point of views for one problem and discuss topics of common interest:
http://www.sitepoint.com/forums/forumdisplay.php?f=15 (JavaScript forum)
http://old.nabble.com/jQuery-General-Discussion-f15494.html (jQuery mailing lists)
http://groups.google.com/group/comp.lang.javascript/ (JavaScript group)
1. What is the point of preferring jQuery's own "document ready" statement to the more common, plain JavaScript
window.onload?
A. It's easier to remember and does the very same thing.
B. The page loads faster.
C. We know when jQuery is ready to operate.
D. We don't have to load the whole library.
2. What are callback functions used for?
A. To make the code nicer to look at.
B. To make things even harder to understand.
C. For backwards compatibility.
D. To execute code right after another event has finished.
3. How can developers add functionalities to the core jQuery module?
A. By developing plugins.
B. By creating patches.
C. By asking the jQuery development team.
D. They can't.
4. Can plugins be used by anybody other than the programmer?
A. Absolutely.
B. Just friends.
C. Nope.
5. How can plugins make use of jQuery's own methods?
A. It's impossible to access jQuery methods.
B. Through the API.
C. Patching the original code.
D. Using a third-party framework.
To sum it all up, in this chapter we've learned a bit of background about the jQuery library, as well as much interesting information related to its development and usage.
An important point is the one concerning basic jQuery usage, which should come naturally by now. Writing plugins is not so different to coding jQuery scripts, and this should be clear, but requires a little knowledge of what this all is about—we just started to get into this, more will come later on!
The next chapter is all about jQuery plugin architecture, and will cover topics explaining how plugins actually work and the main points of the plugin writing process.