Tutorials:How jQuery Works
From jQuery JavaScript Library
A basic introduction to jQuery and the concepts that you need to know to use it.
Original: http://docs.jquery.com/Tutorials:How_jQuery_Works
Author: John Resig.
Contents |
The Basics
This is a basic tutorial, designed to help you get started using jQuery. If you don't have a test page setup yet, start by creating a new HTML page with the following contents:
<html>
<head>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
// Your code goes here
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>
Edit the src attribute in the script tag to point to your copy of jquery.js.
For example, if jquery.js is in the same directory as your HTML file, you
can use:
<script type="text/javascript" src="jquery.js"></script>
You can download your own copy of jQuery from the Downloading jQuery page.
Launching Code on Document Ready
The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
window.onload = function(){ alert("abc") }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is due to the fact that the HTML 'document' isn't finished loading yet, when you first try to run your code.
To circumvent both problems, jQuery has a simple statement that you can use, known as the ready event:
$(document).ready(function(){
// Your code here
});
This code checks the document and waits until it's ready to be manipulated - which is just what we want. So take the above snippet and stick it into the script area on your test page. The remaining jQuery examples will need to be placed inside this callback function, so they are executed when the document is ready to be worked on.
Making Something Happen on Click
The first thing we're going to try is having something happen whenever a link is clicked. In the ready function (from the example above), add the following:
$("a").click(function(){
alert("Thanks for visiting!");
});
Of course, you'll also need to add a link within the <body> of your HTML file:
<body> <a href="http://jquery.com">jQuery</a> </body>
Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser's alert pop-up, before leaving to go to the main jQuery page.
For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler:
$("a").click(function(event){
event.preventDefault();
alert("Thanks for visiting!");
alert("This is my alert");
});
Adding a Class
Another thing that is a common task is the addition (or removal) of classes from elements, for example:
$("a").addClass("test");
if you were to add some style information into the header of your script, like this:
<style type="text/css">a.test { font-weight: bold; }
</style>
and then added the above addClass call - all your A elements would now be bold. To remove the class, you'd use removeClass
Special Effects
In jQuery, a couple handy effects are provided, to really make your web site stand out. To put this to the test, change the click that you added earlier to this:
$("a").click(function(event){
event.preventDefault();
$(this).hide("slow");
});
Now, if you click any link, it should make itself slowly disappear.
Chainability (The Magic of jQuery)
jQuery uses an interesting concept to make its code short and simple. For those familiar with object-oriented programming, this concept should be rather straightforward.
In a nutshell: Every method within jQuery returns the query object itself, allowing you to 'chain' upon it, for example:
$("a").addClass("test").show().html("foo");
Each of those individual methods (addClass, show, and html) return the jQuery object, allowing you to continue applying methods to the current set of elements.
You can take this even further, by adding or removing elements from the selection, modifying those elements and then reverting to the old selection, for example:
$("a")
.filter(".clickme")
.click(function(){
alert("You are now leaving the site.");
})
.end()
.filter(".hideme")
.click(function(){
$(this).hide();
return false;
})
.end();
Which would work against the following HTML:
<a href="http://google.com/" class="clickme">I give a message when you leave</a> <a href="http://yahoo.com/" class="hideme">Click me to hide!</a> <a href="http://microsoft.com/">I'm a normal link</a>
Methods that modify the jQuery selection, and that can be undone with end(), are the following:
-
add(), -
children(), -
eq(), -
filter(), -
find(), -
gt(), -
lt(), -
next(), -
not(), -
parent(), -
parents()and -
siblings().
Please check the Traversing API documentation for details of these methods.
Callbacks and Functions
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes.
Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.
Callback without arguments
For a callback with no arguments you pass it like this:
$.get('myhtmlpage.html', myCallBack);
Note that the second parameter here is simply the function name (but not as a string and without parentheses). Functions in Javascript are 'First class citizens' and so can be passed around like variable references and executed at a later time.
Callback with arguments
"What do you do if you have arguments that you want to pass?", you might ask yourself.
Wrong
The Wrong Way (will not work!)
$.get('myhtmlpage.html', myCallBack(param1, param2));
This will not work because it calls myCallBack(param1, param2) then passes the return value as the second parameter to $.get().
Right
The Right Way ( note the use of function(){ preceding myCallBack() )
$.get('myhtmlpage.html', function(){
myCallBack(param1, param2);
});
So, by passing in an anonymous function (the part with...
function(){
myCallBack(param1, param2);
}
...which itself calls your function with arguments), you're done.
This method works because it passes the anonymous function as the second parameter to $.get() without executing it first.
More Reading
jQuery users have developed a number of helpful tutorials to help guide you, the new jQuery user, through the process of learning how to best use this library. Again, if we could not describe properly the features of the jQuery-library... simply let us know about it.
From here, you should probably begin looking at the rest of the Documentation - it's very comprehensive and covers all aspects of jQuery. If you have any questions, please feel free to send a message to the mailing list.
Categories: JQuery Core | Selectors | CSS | Traversing | Manipulation | Events | Effects | Tutorials