Friday, 25 November 2011
What is jQuery?
Getting started
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!
<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
<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
<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
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
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
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.
Fading elements
Doing simple animation is very easy with jQuery. One of the effects it supports out-of-the-box, is fading an element in and out of visibility. Here's a simple example, where we fade in an otherwise hidden box, using the fadeIn() method:
<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").fadeIn();
}
</script>
You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds. Here's an example of it in use:
<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").fadeIn("fast");
$("#divTestArea22").fadeIn("slow");
$("#divTestArea23").fadeIn(2000);
}
</script>
Don't mind all the HTML, it's just there so that you can see the difference between the fading durations. 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 fadeOut() method, which obviously has the reverse effect of fadeIn():
<div id="divTestArea3" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
$("#divTestArea3").fadeIn(2000, function()
{
$("#divTestArea3").fadeOut(3000);
});
});
</script>
There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it's very easy to use. Here's a little example:
<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").fadeToggle("slow");
}
</script>
And that's how easy it is to use the fading effects of jQuery.
Sliding elements
<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
<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
<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
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()]
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()]
<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
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
<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
<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
<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.