jQuery: 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 the following HTML page:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
// Your code goes here.
</script>
</body>
</html>
Launching Code on Document Ready
To ensure that their code runs after the browser finishes loading the document, many JavaScript programmers wrap their code in an
onload
function:window.onload = function() {
alert( "welcome" );
}
Unfortunately, the code doesn't run until all images are finished downloading, including banner ads. To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the ready event:
$( document ).ready(function() {
// Your code here.
});
For example, inside the
ready
event, you can add a click handler to the link:$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "Thanks for visiting!" );
});
});
For
click
and most other events, you can prevent the default behavior by calling event.preventDefault()
in the event handler:$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "As you can see, the link no longer took you to jquery.com" );
event.preventDefault();
});
});
Complete Example
The following example illustrates the click handling code discussed above, embedded directly in the HTML
<body>
. Note that in practice, it is usually better to place your code in a separate JS file and load it on the page with a <script>
element's src
attribute.<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>
Adding and Removing an HTML Class
Important: You must place the remaining jQuery examples inside the
ready
event so that your code executes when the document is ready to be worked on.
Another common task is adding or removing a class.
First, add some style information into the
<head>
of the document, like this:<style>
a.test {
font-weight: bold;
}
</style>
Next, add the .addClass() call to the script:
$( "a" ).addClass( "test" );
All
<a>
elements are now bold.
To remove an existing class, use .removeClass():
$( "a" ).removeClass( "test" );