Link to jQuery’s Source Code Remotely
This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your
<script> tag should look:
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>
Running Code Unobtrusively When the DOM is Ready
The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).
Here is what it looks like:
- $(document).ready(function() {
-
- });
Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.
Selecting Elements in jQuery
The jQuery library allows you to select elements in your HTML by wrapping them in
$("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:
- $("div");
- $("#myElement");
- $(".myClass");
- $("p#myElement");
- $("ul li a.navigation");
jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:
- $("p > a");
- $("input[type=text]");
- $("a:first");
- $("p:odd");
- $("li:first-child");
jQuery also allows the use of its own custom selectors. Here are some examples:
- $(":animated");
- $(":button");
- $(":radio");
- $(":checkbox");
- $(":checked");
- $(":header");
View a list of jQuery’s selectors and custom selectors
Manipulating and Accessing CSS Class Names
jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:
- $("div").addClass("content");
- $("div").removeClass("content");
- $("div").toggleClass("content");
You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an
if statement. Here is an example:
- if ($("#myElement").hasClass("content")) {
-
- }
You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.
Manipulating CSS Styles with jQuery
CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:
- $("p").css("width", "400px");
- $("#myElement").css("color", "blue")
- $("ul").css("border", "solid 1px #ccc")
View more CSS-related commands for jQuery
Adding, Removing, and Appending Elements and Content
There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).
Get the HTML of any element (similar to innerHTML in JavaScript):
- var myElementHTML = $("#myElement").html();
If you don’t want to access the HTML, but only want the text of an element:
- var myElementHTML = $("#myElement").text();
Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:
- $("#myElement").html("<p>This is the new content.</p>");
- $("#myElement").text("This is the new content.");
To append content to an element:
- $("#myElement").append("<p>This is the new content.</p>");
- $("p").append("<p>This is the new content.</p>");
jQuery also offers use of the commands
appendTo(),
prepend(),
prependTo(),
before(),
insertBefore(),
after(),
insertAfter(), which work similarly to append but with their own unique characteristics that go beyond the scope of this simple tutorial.
View more info on some of the above commands
Dealing with Events in jQuery
Specific event handlers can be established using the following code:
- $("a").click(function() {
-
-
- });
The code inside
function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:
blur,
focus,
hover,
keydown,
load,
mousemove,
resize,
scroll,
submit,
select.
View a more comprehensive list of jQuery events
Showing and Hiding Elements with jQuery
The syntax for showing, hiding an element (or toggling show/hide) is:
- $("#myElement").hide("slow", function() {
-
- }
-
- $("#myElement").show("fast", function() {
-
- }
-
- $("#myElement").toggle(1000, function() {
-
- }
Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.
You can also specifically choose to fade an element in or out, which is always done by animation:
- $("#myElement").fadeOut("slow", function() {
-
- }
-
- $("#myElement").fadeIn("fast", function() {
-
- }
To fade an element only partially, either in or out:
- $("#myElement").fadeTo(2000, 0.4, function() {
-
- }
The second parameter (0.4) represents “opacity”, and is similar to
the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.
jQuery Animations and Effects
You can slide elements, animate elements, and even
stop animations in mid-sequence. To slide elements up or down:
- $("#myElement").slideDown("fast", function() {
-
- }
-
- $("#myElement").slideUp("slow", function() {
-
- }
-
- $("#myElement").slideToggle(1000, function() {
-
- }
To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:
- $("#myElement").animate(
- {
- opacity: .3,
- width: "500px",
- height: "700px"
- }, 2000, function() {
-
- }
- );
Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a
special plugin). It’s worth taking the time to learn to use the animate command in depth, but it is quite easy to use even for beginners.
More info on the animate() command
More info on other effects-related jQuery commands