jQuery Introduction

Updated 7/12/2014 at 6:45pm

What is jQuery?

jQuery is a collection (library) of JavaScript functions.

These functions allow you to do more with less code.

I mentioned in the previous two (JavaScript) handouts that this course does not try to make you into a JavaScript expert. In the same manner, I am not trying to make you into a jQuery expert. But because jQuery is becoming so commonly used in Web sites, I want you to be at least exposed to it.

Also as a reminder from last week's handouts, a function in JavaScript is a named group of code that you can use to accomplish something in your Web page. You have seen several built-in JavaScript functions such as alert(), document.write(), and prompt().

Here is an important point to keep in mind as you look at the jQuery information: You could write your own JavaScript code to do what jQuery does. jQuery is not magic. jQuery is written in JavaScript. But jQuery does a lot of the work for you, and can make your job a lot easier. It is worth the effort to become familiar with jQuery.

The jQuery library (meaning, jQuery's collection of functions) contains the following features, which are designed to make your job easier. You will not need to understand the last half of this list for this class, but your understanding of the first half of this list is what I am hoping for in this introduction to jQuery. (You can take the JavaScript and jQuery class in the fall, if you wish, to get a deeper understanding. That class is ITSE 1311.)


Adding the jQuery Library to your HTML Page

The jQuery library is stored in a single JavaScript source/include file which contains all of the jQuery functions. You must include the jQuery library file into your HTML page before you can use the jQuery functions.

You include the jQuery library file in your HTML page with a standard JavaScript source/include <script> tag in the <head> section, like this:

  <head>
    .
    .
    <script type="text/javascript" src="jquery.js"></script>
    .
    .
  </head> 

The sample <script> tag shown above, assumes that you have stored a copy of the jQuery include file in your own directory, locally or at your Web site, or both.

To use a local copy of the jQuery library as the source/include file, you will need to download the source/include file and save it to a local directory, for your local testing.

Then when you are ready to upload your HTML page to your Web server, you will also need to upload the jQuery library's source/include file to your Web server.

When you download the jQuery library source/include file to your local directory, you can save it as its original, version-specific filename, or you can rename the file to jquery.js. I recommend that you rename it to jquery.js so you don't have to be constantly changing your HTML pages when an upgraded file becomes available.

You can download and save one of two versions of the jQuery library. One version is compressed; the other version is uncompressed. I recommend that you download the uncompressed version of the library file while you are working on the page, and then get the compressed version when you are ready to publish your site.

You can download either version of the jQuery library file here:

http://docs.jquery.com/Downloading_jQuery#Download_jQuery



You can, instead of downloading the jQuery library, include the jQuery library's file from one of several "cloud" Web servers which have been set up specifically for this purpose. If you want to use one of these "cloud" storage areas (also known as Content Delivery Networks, or CDNs) as the source for your jQuery libary include file, you can find some instructions here:

CDN Instructions.

Simply click the link for the CDN that you want to use (for instance: Google CDN); then highlight, copy, and past the <script> tag that you see in that section, to your page's <head> section.



jQuery Syntax

jQuery was designed to make it easy for you to:

In keeping with this design goal, the basic syntax of jQuery is:

  $(selector).action()

Please note these important points about the above syntax:

Here are some examples of jQuery statements, each one of which uses the jQuery syntax given above:


The Document Ready Function

It would not be good for you to use any of jQuery's functions before the HTML page has finished loading into the browser. In order to make sure that the page has finished loading into the browser, jQuery provides a main function that you should use to contain all of the other jQuery functions that you use.

This main container function is $(document).ready(). The other jQuery function calls which it contains, can run only after the HTML page (document) has been loaded and is ready for jQuery commands.

The $(document).ready() function is used like this:

  <script type="text/javascript">
    /* <![CDATA[ */
    $(document).ready(function()
    {
    
       // jQuery code goes here...
    
    });
    /* ]]> */
  </script>

We will see specific examples of its use shortly....


The Anonymous Function

Most jQuery code uses an odd-looking function, without a name, to accomplish its actions.

This odd-looking function is actually a standard JavaScript anonymous function.

An anonymous function is a function that is not given a name when it is created. You can't reference (use) an anonymous function after it has been defined (created), but you can reference (use) it at the time that it is defined (created).

In somewhat plainer language, the above paragraph means that the anonymous function is created and used at the same time.

Look at the sample code later in this handout to see how anonymous functions are used in jQuery code.


jQuery Selectors

jQuery selectors allow you to select HTML elements (or groups of elements) by element name, by attribute name, or by specific content. They select (query) the HTML elements/tags that you want to apply an effect/action to.

There are three kinds of jQuery selectors:

  1. Basic (tag) jQuery Selectors
  2. jQuery Attribute Selectors
  3. jQuery Content Selectors

There is an excellent jQuery Selector reference page at w3schools.com.

The pages which most helped me to make sense of the various types of jQuery selectors are at
http://api.jquery.com/category/selectors/, especially the sections under "Selectors" which are
"Basic",
"Attribute", and
"Content Filter".


Basic Selectors

The Basic Selectors are based on the Cascading Style Sheet 1 specification, as outlined by the W3C. Here are some examples:


Attribute Selectors

You use Attribute Selectors to select HTML elements (tags) with given attributes. Attribute values in selector expressions must be surrounded by quotation marks. (jQuery's Attribute Selectors use what are known as XPath expressions.)

Also note that the syntax of attribute selectors (and XPath expressions) includes square brackets around the attribute information in the jQuery selector.

Also note that the syntax of attribute selectors includes an additional set of quotes if the selector itself has quotes in it.

Here are some examples of attribute selectors:


Content Filters

jQuery Content filters can be used to select elements based on the element's specific contents.

Here are some examples:


jQuery Example 1

This first jQuery example is file jQuerySample1.html. Click the various buttons at the top of the sample page to see the effects which jQuery is being used to accomplish.

Here is this sample page's code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery Sample 1</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    /* <![CDATA[ */
    $(document).ready(function()
    {
      $("#buttonOneA").click(function(){
    $("#firstP").hide();
    });
      $("#buttonOneB").click(function(){
    $("#firstP").show();
    });
      $("#buttonTwoA").click(function(){
    $("#secondP").hide();
    });
      $("#buttonTwoB").click(function(){
    $("#secondP").show();
    });
    });
    /* ]]> */
  </script>
  
  <style type="text/css">
    body { font-family: Arial,sans-serif; }
    #mainDiv { width: 800px; height: 600px; margin: 0 auto; position: relative; border: 1px solid gray; border-radius: 20px; padding: 20px; }
    #firstP { background-color: #dff; width: 400px; position: absolute; left: 20px; top: 100px; padding: 1em; }
    #secondP { background-color: #fdf; width: 400px; position: absolute; left: 20px; top: 300px; padding: 1em; }
  </style>
</head>

<body>
  <div id="mainDiv">
  <h3>jQuery Sample 1</h3>
  <div id="buttons">
    <button id="buttonOneA">Hide Paragraph One</button>
    <button id="buttonOneB">Show Paragraph One</button>
    <button id="buttonTwoA">Hide Paragraph Two</button>
    <button id="buttonTwoB">Show Paragraph Two</button>
  </div>
    <p id="firstP">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla 
    felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum 
    tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper 
    quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
    </p>
    <p id="secondP">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla 
    felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum 
    tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper 
    quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
    </p>
  </div>
</body>
</html>

Please note these points about the above code:


jQuery Example 2

This second jQuery example is file jQuerySample2.html. Roll your mouse cursor over each of the text blocks (paragraphs) to see the jQuery effects.

Here is this sample page's code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery Example 2</title>
  <link rel="stylesheet" type="text/css" href="jsStuff.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    /* <![CDATA[ */
    $(document).ready(function()
    {
      $("p").mouseover(function(){$(this).css({'color': 'red', 'text-decoration':'underline'});});
      $("p").mouseout(reduceText);
    });
  
    function reduceText()
    {
      var cssObj = {'color': 'black', 'text-decoration': 'none'};
      $(this).css(cssObj);
    }
    /* ]]> */
  </script>
</head>

<body>
  <div id="mainDiv2">
    <h3>Second jQuery Example</h3>
    <p id="firstP">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
    </p>
    <p id="secondP">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
    </p>
  </div>
</body>
</html>

Please note these points about the above code: