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() {
- // all jQuery code goes here
- });
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"); // selects all HTML div elements
- $("#myElement"); // selects one HTML element with ID "myElement"
- $(".myClass"); // selects HTML elements with class "myClass"
- $("p#myElement"); // selects paragraph elements with ID "myElement"
- $("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items
- $("p > a"); // selects anchors that are direct children of paragraphs
- $("input[type=text]"); // selects inputs that have specified type
- $("a:first"); // selects the first anchor on the page
- $("p:odd"); // selects all odd numbered paragraphs
- $("li:first-child"); // every list item that's first child in a list
- $(":animated"); // selects elements currently being animated
- $(":button"); // selects any button elements (inputs or buttons)
- $(":radio"); // selects radio buttons
- $(":checkbox"); // selects checkboxes
- $(":checked"); // selects selected checkboxes or radio buttons
- $(":header"); // selects header elements (h1, h2, h3, etc.)
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"); // adds class "content" to all <div> elements
- $("div").removeClass("content"); // removes class "content" from all <div> elements
- $("div").toggleClass("content"); // toggles the class "content" on all <div> elements (adds it if it doesn't exist, and removes it if it does)
if
statement. Here is an example:- if ($("#myElement").hasClass("content")) {
- // do something here
- }
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"); // adds a width to all paragraphs
- $("#myElement").css("color", "blue") // makes text color blue on element #myElement
- $("ul").css("border", "solid 1px #ccc") // adds a border to all lists
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(); // variable contains all HTML (including text) inside #myElement
- var myElementHTML = $("#myElement").text(); // variable contains all text (excluding HTML) inside #myElement
- $("#myElement").html("<p>This is the new content.</p>"); // content inside #myElement will be replaced with that specified
- $("#myElement").text("This is the new content."); // text content will be replaced with that specified
- $("#myElement").append("<p>This is the new content.</p>"); // keeps content intact, and adds the new content to the end
- $("p").append("<p>This is the new content.</p>"); // add the same content to all paragraphs
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() {
- // do something here
- // when any anchor is clicked
- });
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() {
- // do something once the element is hidden
- }
- $("#myElement").show("fast", function() {
- // do something once the element is shown
- }
- $("#myElement").toggle(1000, function() {
- // do something once the element is shown/hidden
- }
You can also specifically choose to fade an element in or out, which is always done by animation:
- $("#myElement").fadeOut("slow", function() {
- // do something when fade out finished
- }
- $("#myElement").fadeIn("fast", function() {
- // do something when fade in finished
- }
- $("#myElement").fadeTo(2000, 0.4, function() {
- // do something when fade is finished
- }
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() {
- // do something when slide down is finished
- }
- $("#myElement").slideUp("slow", function() {
- // do something when slide up is finished
- }
- $("#myElement").slideToggle(1000, function() {
- // do something when slide up/down is finished
- }
- $("#myElement").animate(
- {
- opacity: .3,
- width: "500px",
- height: "700px"
- }, 2000, function() {
- // optional callback after animation completes
- }
- );
More info on the animate() command
More info on other effects-related jQuery commands