jQuery

First Steps

Basics# Locate jQuery Selectors Syntax Launching code


In this tutorial:


Applying jQuery

jQuery is a JavaScript single file. One way to use jQuery is to download the jQuery library to your local machine, and include it on the pages you wish to use it.

Download jQuery

Use CDN

CDN

You can use also external servers called CDN (Content Delivery Network) instead of downloading the jQuery file to the local machine. A CDN is a network of geographically dispersed servers. It is a way to deliver content from your website to people more quickly and efficiently, based on their geographic location. The main benefit of having jQuery on a CDN is that the files can be downloaded in parallel to files downloaded from your own website, and other users may have already cached jQuery from CDN. Thus, the loading is faster. Google, Microsoft, and others provide CDNs that host scripts such as jQuery. For example, to use Microsoft, include the following in the head element:

<script src="//ajax.microsoft.com/ajax/jquery/jquery-[version].js"> </script> 

For google CDN go to Google Hosted Libraries. Search there for jQuery snippet. Copy the script line and put it in the head element.

Using CDN and Downloaded jQuery

CDN may not be available all the time (if it is down). In such a case we have to use the local jQuery version (downloaded file). Thus, it is recommended to provide a fallback with the local jQuery. Use the CDN first, and if it fails, load the local copy. For example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/[version]/jquery.min.js"></script>
<script> window.jQuery || document.write('<script src="scripts/jquery.js"></script>') </script>

jQuery Selectors

Selectors allow you to find DOM elements and then manipulate them by jQuery functions. With jQuery, single or multiple elements can be selected in an easy way. You can find elements using normal JavaScript, however elements selection in JavaScript is more complicated and raises cross-browser issues.

If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re almost the same thing and use almost the same syntax.

jQuery provides a special utility function to select elements. It is called $. A $ sign defines jQuery ( $ === jQuery ). $ is identical to calling jQuery function.

Selector syntax (2 ways):

$(selector)
jQuery( selector )

Where selector is a selector expression (like in CSS) written in a single or double quotes.

Example:

$('div')   selects all <div> elements.
$('p, #my-id, a')   selects all <p> elements, an element which id is my-id, and all <a> elements.

Once you've made a selection, you'll often want to know whether you have anything to work with. You may be inclined to try something like:

if ($('div.foo').length) { ... }

The partial selectors list is shown in the following table. You can combine selectors in the same way as in CSS. For the full list see jQuery Selectors.

JQuery CSS Partial Reference
Selector Description
.className Selects all elements with the specified class
#idName Selects an element with the specified ID
* Universal selector: selects every element in the document
element Selects every element of the specified type
parent > child Selects all children of the parent element
anscestor descendant Selects all descendants of the parent element
previous + next Selects the next sibling of the previous element
previous ~ siblings Selects all siblings of the element
:odd Filters the current selector to only include odd numbered elements
:even Filters the current selector to only include the even numbered matches
:first Filters the current selector to only include the first match
:parent Filters the current selector to only include the element if it is an element of that type AND a parent
:not() Filters the current selector so that it doesn't include the selector passed to not() as an argument

jQuery Basic Syntax

jQuery basic syntax:

$(selector).action()

This means:

#

Example:

$('div').hide() - Hides all <div> elements.
jQuery('div').hide() - Hides all <div> elements.
$('.my-class').hide() - Hides all elements with class="my-class".
$('#my-id').hide() - Hides the element with id="my-id".
$(this).hide() - Hides the current element.

See jQuery Selectors on this page.


Launching Code on Document Ready

In the JavaScript lecture we saw how to run JavaScript code after the the browser finishes loading the document. In this case the code doesn't run until all images are finished downloading, including banner ads. By using jQuery we can run the code before all the images and all the CSS have loaded. This is done with the .ready() event:

// using pure JavaScript wait for ALL are loaded (DOM, images, CSS ...)
window.onload = function() {
    // Your code here
};

// using jQuery ready
// use $(document).ready() to detect when a page and DOM hierarchy
// has loaded and is ready to use, but before images and all CSS are loaded.
// allows to start manipulate DOM early
$(document).ready(function() {
    // Your code here
});

Best practice is to include all stylesheets before including jQuery.

You can use $(document).ready() multiple times in your code.

To launch the code after all images are loaded use:

$(window).load(function(){
    // Code after images are loaded
});

Advanced Stuff

There are different types of Document Ready functions typically used in jQuery. One of them was introduced above. The equivalent way is:

$(function(){
    // Your code here
});

By default, jQuery uses $ as a shortcut for jQuery. Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery. In order to avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page. For more details see here.

There are other ways to avoid $ conflict with other libraries. For example:

// Import other library
// Import jQuery
jQuery.noConflict();
jQuery(document).ready(function($) {
   // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.

Note: To avoid conflicts sometimes we can invoke imediate function by:

(function ($) {
   // Your jQuery code here, using the $
    .......
})(jQuery); // passing jquery to avoid any conflict with other libraries.