1.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, likeAJAX
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.
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
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.
2.How to Use this.
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:
<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:
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.
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.
3. 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:
<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:
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.
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.
4. 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:
<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:
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.
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.
5. 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:
$("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.
Selectors can do much more for you though. Read on for more cool examples.
6. 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.
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:
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:
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.
7. 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.
8. 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:
<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:
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:
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>
9. 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:
<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:
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:
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:
<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:
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.
10. 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.
11. 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:
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:
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
jQuery css() Method
jQuery has one important
method for CSS manipulation: css()
The css() method has three
different syntaxes, to perform different tasks.
- css(name) - Return CSS property value
- css(name,value) - Set CSS property and value
- css({properties}) - Set multiple CSS properties and values
jQuery Syntax Examples
$(this).hide()
Demonstrates the jQuery hide() function, hiding the current HTML element.
Demonstrates the jQuery hide() function, hiding the current HTML element.
$("#test").hide()
Demonstrates the jQuery hide() function, hiding the element with id="test".
Demonstrates the jQuery hide() function, hiding the element with id="test".
$("p").hide()
Demonstrates the jQuery hide() function, hiding all <p> elements.
Demonstrates the jQuery hide() function, hiding all <p> elements.
$(".test").hide()
Demonstrates the jQuery hide() function, hiding all elements with class="test".
Demonstrates the jQuery hide() function, hiding all elements with class="test".
jQuery Attribute Selectors
jQuery uses XPath expressions to select elements with given
attributes.
$("[href]") select all elements with an href attribute.
$("[href='#']") select all elements with an href value
equal to "#".
$("[href!='#']") select all elements with an href
attribute NOT equal to "#".
$("[href$='.jpg']") select all elements with an href
attribute that ends with ".jpg".
Comments
Post a Comment