Showing posts with label tutorials. Show all posts
Showing posts with label tutorials. Show all posts
Friday, 25 November 2011
What is jQuery?
Since you've come to this page, you may already have a pretty good idea about what jQuery is, but to be on the safe side, here is a brief explanation. jQuery is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe jQuery as an abstraction layer, since it takes a lot of the functionality that you would have to write many lines of JavaScript to accomplish and wraps it into functions that you can call with a single line of code. It's important to note that jQuery does not replace JavaScript, and while it does offer some syntactical shortcuts, the code you write when you use jQuery is still JavaScript code. With that in mind, you should be aware that you don't need to be a JavaScript expert to use jQuery. In fact, jQuery tries to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation, so that you may do these things without knowing a lot about JavaScript. There are a bunch of other JavaScript frameworks out there, but as of right now, jQuery seems to be the most popular and also the most extendable, proved by the fact that you can find jQuery plugins for almost any task out there. The power, the wide range of plugins and the beautiful syntax is what makes jQuery such a great framework. Keep reading to know much more about it and to see why we recommend it.
Getting started
To use jQuery, you need to include it on the pages where you wish to take advantage of it. You can do this by downloading jQuery from their website at www.jquery.com. There is usually a choice between a "Production" version and a "Development" version. The first is for your live website, because it has been minified and compressed to take up the least amount of space, which is important for your visitors, whose browser will have to download the jQuery file along with the rest of your website. For testing and development, the "Development" version is best. It hasn't been minified or compressed, so when you run into an error, you can actually see where in jQuery it happens.
Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:
A part of your page should now look something like this:
A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.
You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:
I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:
http://code.google.com/intl/da/apis/libraries/devguide.html#jquery
Or if you prefer to use it from Microsoft:
http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0
Read on to learn how to start using jQuery.
Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:
<script type="text/javascript" src="jquery-1.5.1.js"></script>
A part of your page should now look something like this:
<head>
<title>jQuery test</title>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
</head>
A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.
You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:
http://code.google.com/intl/da/apis/libraries/devguide.html#jquery
Or if you prefer to use it from Microsoft:
http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0
Read on to learn how to start using jQuery.
Hello, world!
Every decent programming tutorial will start with a "Hello, world!" example and this tutorial is yet another one of them. In the previous chapter, we learned how to include jQuery on our page, so that we may start using all of its great features. You need to know a bit more about how jQuery works, before you can start writing your own code, but just to make sure that everything is working, and for you to see how simple jQuery is, let's kick off with a little example:
Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.
Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:
And it would be even longer if our HTML element didn't have an ID, but for instance just a class.
Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.
Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:
<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>
And it would be even longer if our HTML element didn't have an ID, but for instance just a class.
Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.
The ready event
As mentioned in the previous chapter, it's good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the "Hello, world!" chapter, but this time the code is inside the ready event:
What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.
However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:
But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.
As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.
<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
$("#divTest1").text("Hello, world!");
}
$(document).ready(DocumentReady);
</script>
What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.
However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:
<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
$("#divTest2").text("Hello, world!");
});
</script>
But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
<div id="divTest3"></div>
<script type="text/javascript">
$(function()
{
$("#divTest3").text("Hello, world!");
});
</script>
In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.
As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.
Method chaining
Yet another one of the really cool aspects of jQuery is the fact that most of the methods returns a jQuery object that you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once. Here's an example, and don't worry about the jQuery methods used in the following examples - they will be explained in later chapters:
It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.
We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:
JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.
Note that some methods doesn't return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!").css("color", "blue");
</script>
It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.
We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:
<div id="divTest2"></div>
<script type="text/javascript">
$("#divTest2").text("Hello, world!")
.removeClass("blue")
.addClass("bold")
.css("color", "blue");
</script>
JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.
Note that some methods doesn't return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.
Introduction to jQuery selectors
A very common task when using JavaScript is to read and modify the content of the page. To do this, you need to find the element(s) that you wish to change, and this is where selector support in jQuery will help you out. With normal JavaScript, finding elements can be extremely cumbersome, unless you need to find a single element which has a value specified in the ID attribute. jQuery can help you find elements based on their ID, classes, types, attributes, values of attributes and much, much more. It's based on CSS selectors and as you will see after going through this tutorial, it is extremely powerful.
Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:
$(<query here>)
With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.
Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:
$(<query here>)
With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.
Using elements, ID's and classes
The #id selector
A very common selector type is the ID based, which we saw in the "Hello, world" example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:
$("#divTest")
An example of it in use:
<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
$("#divTest").text("Test");
});
</script>
Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.
The .class selector
Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:
<ul>
<li class="bold">Test 1</li>
<li>Test 2</li>
<li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
$(".bold").css("font-weight", "bold");
});
</script>
The element selector
You can also match elements based on their tag names. For instance, you can match all links on a page like this:
$("a")
Or all div tags like this:
$("div")
If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");
This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.
Selectors can do much more for you though. Read on for more cool examples.
Using attributes
In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.
The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:
We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.
Here's an example where we find elements with a specific value:
The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
The difference is the != instead of =, a common way of negating an operator within many programming languages.
And there's even more possibilities:
Find elements with a value which starts with a specific string using the ^= operator:
Find elements with a value which ends with a specific string using the $= operator:
Find elements with a value which contains a specific word:
Find elements with a specific attribute
The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:
<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />
<script type="text/javascript">
$(function()
{
$("[title]").css("text-decoration", "underline");
});
</script>
We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.
Find elements with a specific value for a specific attribute
Here's an example where we find elements with a specific value:
<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />
<script type="text/javascript">
$(function()
{
$("a[target='_blank']").append(" [new window]");
});
</script>
The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");
The difference is the != instead of =, a common way of negating an operator within many programming languages.
And there's even more possibilities:
Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");
Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");
Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");
Parent/child relation selectors
jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element.
The syntax for finding children which are direct descendants of an element looks like this:
$("div > a")
This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:
$("div a")
Here's an example where we color bold tags blue if they are directly descending from the first test area:
As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.
The syntax for finding children which are direct descendants of an element looks like this:
$("div > a")
This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:
$("div a")
Here's an example where we color bold tags blue if they are directly descending from the first test area:
<div id="divTestArea1">
<b>Bold text</b>
<i>Italic text</i>
<div id="divTestArea2">
<b>Bold text 2</b>
<i>Italic text 2</i>
<div>
<b>Bold text 3</b>
</div>
</div>
</div>
<script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");
</script>
As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:
<div id="divTestArea1">
<b>Bold text</b>
<i>Italic text</i>
<div id="divTestArea2">
<b>Bold text 2</b>
<i>Italic text 2</i>
<div>
<b>Bold text 3</b>
</div>
</div>
</div>
<script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");
</script>
Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.
Sliding elements
In the previous chapter, we saw how we could fade elements in and out of visibility using the fading methods of jQuery. However, sometimes a sliding effect is a better choice, and for that, jQuery has a set of matching methods for doing just that. Let's kick off with a simple example of it, where we use the slideDown() method:
For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds.Let's try an example where we do just that:
There's a bit more HTML than usual, but that's only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.
Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the slideUp() method:
The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.
In case you want to simply slide an element up or down depending on its current state, the jQuery developers have provided us with a nice slideToggle() method for doing just that. Check out the next example, where we use it:
<div id="divTestArea1" style="padding: 50px;
background-color: #89BC38; text-align: center; display: none;">
<b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
$("#divTestArea1").slideDown();
}
</script>
For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds.Let's try an example where we do just that:
<div id="divTestArea21" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px;
display: none; background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px;
display: none; background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
$("#divTestArea21").slideDown("fast");
$("#divTestArea22").slideDown("slow");
$("#divTestArea23").slideDown(2000);
}
</script>
There's a bit more HTML than usual, but that's only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.
Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the slideUp() method:
<div id="divTestArea3" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
$("#divTestArea3").slideDown(2000, function()
{
$("#divTestArea3").slideUp(3000);
});
});
</script>
The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.
In case you want to simply slide an element up or down depending on its current state, the jQuery developers have provided us with a nice slideToggle() method for doing just that. Check out the next example, where we use it:
<div id="divTestArea4" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
$("#divTestArea4").slideToggle("slow");
}
</script>
Custom animations with the animate() method
In previous chapters, we looked into the built-in fading and sliding effect methods of jQuery. However, you can much more than just that. With the animate() method, you can create custom animations where you manipulate pretty much any numerical CSS property of an element. This allows you to e.g. move a box slowly across the screen or have it jump up and down. Let's try something very simple:
The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:
As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:
It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.
However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:
<div style="height: 60px;">
<div id="divTestBox1" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
$("#divTestBox1").animate(
{
"left" : "200px"
}
);
});
</script>
The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:
<div style="height: 60px;">
<div id="divTestBox2" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
$("#divTestBox2").animate(
{
"left" : "200px"
},
5000
);
});
</script>
As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:
<div style="height: 40px;">
<div id="divTestBox3" style="height: 20px; width: 20px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
$("#divTestBox3").animate(
{ "left" : "100px" },
1000,
function()
{
$(this).animate(
{ "left" : "20px" },
500,
function()
{
$(this).animate({ "left" : "50px" }, 500);
}
)
}
);
});
</script>
It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.
However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:
<div style="height: 40px;">
<div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38;
position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
$("#divTestBox4").animate({ "left" : "100px" }, 1000);
$("#divTestBox4").animate({ "left" : "20px" }, 500);
$("#divTestBox4").animate({ "left" : "50px" }, 500);
});
</script>
Stopping animations with the stop() method
In the previous chapter, we saw how we could do custom animations using the animate() method and how we could have several animations after each other, by making several animation calls and thereby using the animation queue of jQuery. However, sometimes you need to stop an animation before it finishes, and for this, jQuery has the stop() method. It works for all effects related jQuery functions, including sliding, fading and custom animations with the animate() method. Here's an example where we use it:
To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:
We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped.
The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:
Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.
<a href="javascript:void(0);" onclick="$('#divTestArea1').slideDown(5000);">
Show box</a>
<a href="javascript:void(0);" onclick="$('#divTestArea1').stop();">Stop</a>
<div id="divTestArea1" style="padding: 100px; background-color: #89BC38;
text-align: center; display: none;">
<b>Hello, world!</b>
</div>
To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:
<a href="javascript:void(0);" onclick="$('#divTestArea2').slideDown(5000)
.slideUp(5000);">Show box</a>
<a href="javascript:void(0);" onclick="$('#divTestArea2').stop();">Stop</a>
<a href="javascript:void(0);" onclick="$('#divTestArea2').stop(true);">
Stop all</a>
<a href="javascript:void(0);" onclick="$('#divTestArea2').clearQueue().hide();">
Reset</a>
<div id="divTestArea2" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;">
<b>Hello, world!</b>
</div>
We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped.
The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:
<a href="javascript:void(0);" onclick="$('#divTestArea3').slideDown(5000);">
Show box</a>
<a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true);">Stop</a>
<a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true, true);">
Stop but finish</a>
<a href="javascript:void(0);" onclick="$('#divTestArea3').clearQueue().hide();">
Reset</a>
<div id="divTestArea3" style="padding: 100px; background-color: #89BC38;
text-align: center; display: none;">
<b>Hello, world!</b>
</div>
Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.
Introduction to DOM manipulation
One of the most important aspects of JavaScript and thereby jQuery, is manipulation of the DOM. DOM stands for Document Object Model and is a mechanism for representing and interacting with your HTML, XHTML or XML documents. It allows you to navigate and manipulate your documents through a programming language, which in the browser will almost always be JavaScript. DOM navigation and manipulation using standard JavaScript can be pretty cumbersome, but fortunately for us, jQuery comes with a bunch of DOM related methods, making it all much easier.
In the first "Hello, world!" example of this tutorial, we compared the job of finding an element and setting the text of it using first jQuery and then JavaScript. This is just the tip of the iceberg though, and in the upcoming chapters you will see just how easy it is to manipulate the content of your documents with jQuery. Read on.
In the first "Hello, world!" example of this tutorial, we compared the job of finding an element and setting the text of it using first jQuery and then JavaScript. This is just the tip of the iceberg though, and in the upcoming chapters you will see just how easy it is to manipulate the content of your documents with jQuery. Read on.
Getting and setting content [text(), html() and val()]
The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These three things might seem like the same thing, but they're not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for form elements and HTML is the same as text, but including any markup.
Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:
So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:
And that's how easy it is to set text, HTML and values.
These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:
We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.
Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:
<div id="divTest">
<b>Test</b>
<input type="text" id="txtTest" name="txtTest" value="Input field" />
</div>
<script type="text/javascript">
$(function()
{
alert("Text: " + $("#divTest").text());
alert("HTML: " + $("#divTest").html());
alert("Value: " + $("#divTest").val());
alert("Text: " + $("#txtTest").text());
alert("HTML: " + $("#txtTest").html());
alert("Value: " + $("#txtTest").val());
});
</script>
So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:
<div id="divText"></div>
<div id="divHtml"></div>
<input type="text" id="txtTest" name="txtTest" value="Input field" />
<script type="text/javascript">
$(function()
{
$("#divText").text("A dynamically set text");
$("#divHtml").html("<b><i>A dynamically set HTML string</i></b>");
$("#txtTest").val("A dynamically set value");
});
</script>
And that's how easy it is to set text, HTML and values.
These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<script type="text/javascript">
$(function()
{
$("p").text(function(index, oldText) {
return "Existing text: " + oldText + ". New text:
A dynamically set text (#" + index + ")";
});
});
</script>
We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.
Getting and setting attributes [attr()]
In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:
In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:
This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:
The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:
We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.
<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
alert($("#aGoogle1").attr("href"));
});
</script>
In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:
<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
$("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>
This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:
<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
$("#aGoogle3").attr(
{
"href" : "http://www.google.co.uk",
"title" : "Google.co.uk"
});
});
</script>
The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:
<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />
<script type="text/javascript">
$(function()
{
$("a.google").attr("href", function(index, oldValue)
{
return oldValue + "imghp?tab=wi";
});
});
</script>
We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.
Getting and setting CSS classes
Just like it's very easy to manipulate content and attributes of elements, as we saw in the previous chapters, it's equally easy to manipulate the CSS of elements. jQuery gives you easy access to changing both the style attribute, which you manipulate using the css() method, as well as the class(es) of an element, where several different methods lets you modify it.
Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).
I have defined a couple of very simple CSS selectors in my stylesheet, mostly for testing purposes:
In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.
The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:
Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:
First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.
Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).
I have defined a couple of very simple CSS selectors in my stylesheet, mostly for testing purposes:
.bold {
font-weight: bold;
}
.blue {
color: blue;
}
In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.
<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a>
<script type="text/javascript">
function ToggleClass(sender)
{
if($(sender).hasClass("bold"))
$(sender).removeClass("bold");
else
$(sender).addClass("bold");
}
</script>
The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:
<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">
Toggle class</a>
Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:
<div id="divTestArea1">
<span>Test 1</span><br />
<div>Test 2</div>
<b>Test 3</b><br />
</div>
<script type="text/javascript">
$(function()
{
$("#divTestArea1 span, #divTestArea1 b").addClass("blue");
$("#divTestArea1 div").addClass("bold blue");
});
</script>
First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.
The append() and prepend() methods
Adding new stuff to existing elements is very easy with jQuery. There are methods for appending or prepending, taking HTML in string format, DOM elements and jQuery objects as parameters. In the next example, you will see how easy it is to insert new elements in a list, using both the append() and the prepend() method:
We have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:
As you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too.
There are variations of the append() and prepend() methods, called appendTo() and prependTo(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to append/prepend to, with a parameter of what is to be appended/prepended, you do the exact opposite. Which to use obviously depends on the situation, but here's an example showing you how to use them both:
In this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs.
<a href="javascript:void(0);" onclick="$('#olTestList1')
.append('<li>Appended item</li>');">Append</a>
<a href="javascript:void(0);" onclick="$('#olTestList1')
.prepend('<li>Prepended item</li>');">Prepend</a>
<ol id="olTestList1">
<li>Existing item</li>
<li>Existing item</li>
</ol>
We have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:
<a href="javascript:void(0);" onclick="AppendItemsToList();">Append items</a>
<ol id="olTestList2"></ol>
<script type="text/javascript">
function AppendItemsToList()
{
var item1 = $("<li></li>").text("Item 1");
var item2 = "<li>Item 2</li>";
var item3 = document.createElement("li");
item3.innerHTML = "Item 3";
$("#olTestList2").append(item1, item2, item3);
}
</script>
As you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too.
There are variations of the append() and prepend() methods, called appendTo() and prependTo(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to append/prepend to, with a parameter of what is to be appended/prepended, you do the exact opposite. Which to use obviously depends on the situation, but here's an example showing you how to use them both:
<a href="javascript:void(0);" onclick="PrependItemsToList();">Prepend items</a>
<ol id="olTestList3"></ol>
<script type="text/javascript">
function PrependItemsToList()
{
$("#olTestList3").prepend($("<li></li>").text("prepend() item"));
$("<li></li>").text("prependTo() item").prependTo("#olTestList3");
}
</script>
In this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs.
The before() and after() methods
In the previous chapter, we used the append() and prepend() methods to insert stuff inside an element, but in some cases, you need to insert things before or after one or several elements instead. jQuery has the before() and after() methods for just this purpose, and they are just as easy to use. Check out this example:
Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:
In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.
There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both:
In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.
<a href="javascript:void(0);" onclick="$('input.test1')
.before('<i>Before</i>');">Before</a>
<a href="javascript:void(0);" onclick="$('input.test1')
.after('<b>After</b>');">After</a>
<br /><br />
<input type="text" class="test1" value="Input 1" name="txtInput1" /><br />
<input type="text" class="test1" value="Input 2" name="txtInput2" /><br />
Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:
<a href="javascript:void(0);" onclick="InsertElements();">Insert elements</a>
<br /><br />
<span id="spnTest2">Hello world? </span>
<script type="text/javascript">
function InsertElements()
{
var element1 = $("<b></b>").text("Hello ");
var element2 = "<i>there </i>";
var element3 = document.createElement("u");
element3.innerHTML = "jQuery!";
$("#spnTest2").after(element1, element2, element3);
}
</script>
In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.
There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both:
<a href="javascript:void(0);" onclick="InsertElementsBefore();">
Insert elemenets</a>
<br /><br />
<span id="spnTest3">Hello world? </span>
<script type="text/javascript">
function InsertElementsBefore()
{
$("#spnTest3").before($("<i></i>").text("before() "));
$("<b></b>").text("insertBefore() ").insertBefore("#spnTest3");
}
</script>
In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.
The remove() and empty() methods
In the last couple of chapters, we have worked with adding new elements to a page, but of course jQuery can help you remove them as well. There are mainly two methods for this: remove() and empty(). The remove() method will delete the selected element(s), while the empty() method will only delete all child elements of the selected element(s). The following example should illustrate the difference - be sure to click the links in the right order though:
The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.
The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:
We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.
You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.
<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">
empty() div</a>
<a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">
remove() div</a>
<div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
<b>Bold text</b>
<i>Italic text</i>
</div>
The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.
The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:
<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">
remove() more bold</a>
<div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
<b>Bold text</b><br />
<b class="more">More bold text</b><br />
<b class="more">Even more bold text</b><br />
</div>
We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.
You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.
Introduction to events
Events in JavaScript are usually something where you write a snippet of code or a name of a function within one of the event attributes on an HTML tag. For instance, you can create an event for a link by writing code like this:
And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.
<a href="javascript:void(0);" onclick="alert('Hello, world!');">Test</a>
And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
<script type="text/javascript">
$(function()
{
$("a, span").bind("click", function() {
alert('Hello, world!');
});
});
</script>
We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.
Subscribe to:
Posts (Atom)