facebook twitter
Webucator's Free jQuery Tutorial

Lesson: jQuery Intro

Welcome to our free jQuery tutorial. This tutorial is based on Webucator's jQuery Fundamentals Training course.

jQuery is a lightweight, powerful JavaScript library that simplifies the task of front-end scripting on web pages. This lesson introduces jQuery and shows a brief example of some of the library's capabilities.

Lesson Goals

  • Learn what jQuery is.
  • Learn to use jQuery on your own sites.
  • Learn the reasons for the use of a ready handler when invoking jQuery code.
  • Learn some capabilities of jQuery by looking at a quick first example.

jQuery: An Introduction

jQuery is a library that simplifies and extends the use of JavaScript. As the documentation states, jQuery "makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript."

Because it is widley used, thoroughly tested on all commonly used browsers, well documented, and extended by a huge collection of plugins, jQuery makes the process of front-end web coding much simpler than using plain-old JavaScript.

Some of the many benefits of jQuery are:

  1. No need to worry about browser inconsistencies.
  2. Shorter, easier-to-maintain code.
  3. Access to useful, powerful widgets from other developers to make our work easier.

How jQuery Works

jQuery is a large JavaScript library. Including the library on a web page offers you the ability to use all of jQuery's functionality. You might use it to manipulate a page's Document Object Model (DOM) by adding a background color to all divs of a given class or by inserting a new element at the top of a form based on a user's actions. You might use jQuery's Ajax capabilities to pull content from another page on your site or to submit a form without refreshing the page.

When including jQuery, you have the option of downloading it from the jQuery website and hosting it on your own site or you can link to it from a Content Delivery Network (CDN) where it is hosted for you. Consider these two examples of to include the jQuery library on a web page:

Use jQuery CDN

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

Use Local Copy of jQuery

<script src="/js/jquery-3.4.1.min.js"></script>

In the first example, we include jQuery from the jQuery CDN. Using a CDN is generally the way to go because of the performance benefit:

  1. jQuery is so commonly used that your visitor has likely visited another site that used this same CDN. As such, the browser may already have a cached version of the file and won't need to re-download it.
  2. A CDN is likely to have fast, distributed servers, likely as not to be physically closer to your users than your hosting server.

Other CDNs

The jQuery CDN that we used above is not the only CDN for jQuery. See https://jquery.com/download/#other-cdns for a list of others.

If you don't wish to use a CDN, you can download the jQuery library and link to it as shown in the second example above.

Whichever strategy you choose, it is a good idea to use the minified version of jQuer (note the "min" in the file names in the examples above). Minification is the process of stripping whitespace and using shorter identifiers for variable and function names, significantly cutting down the size (and thus the download time) of the file. The minified version works exactly the same as the un-minified version.

In this course...

While we generally recommend using a CDN, we use a local copy of the jQuery library in this course, so that you can work on the class files while offline.

Running Code on Document Ready

Often we will wrap our jQuery code in the ready handler. This ensures that the jQuery code we write does not execute until the DOM has loaded but (usefully) does not wait until all images have downloaded.

This is called the ready handler, because it used to be written like this:

$(document).ready(function() {
  $('a.thanks').click(function(event) {
    alert("Thanks!");
  });
});

While that code still works, it has been deprecated as of version 3 of jQuery in favor of the following shorter style:

$(function() {
  $('a.thanks').click(function(event) {
    alert("Thanks!");
  });
});

Both blocks of code do the same thing: attach a click handler to any a element of class thanks. Users who click on any such link will see a JavaScript alert with the text "Thanks!". Wrapping the code in the ready handler ensures that the handler is active as soon as the page's DOM has loaded. We will cover this concept in more detail later in the course.

A First Example

Let's look at an example of what one might do with jQuery.

Open jqy-intro/Demos/index.html in a browser. The page displays a map of the world with two markers for New York City ("NYC") and London ("LON"):

Map of World Image from Wikipedia Wikipedia

Mousing over either of the city markers expands the containing element, which has a semi-transparent red background, and display some details about the city:

Map of World - with Hover

Let's look at the code.

Code Sample:

jqy-intro/Demos/index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="../../jqy-libs/jquery.js"></script> 
<link href="../../jqy-css/normalize.css" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>jQuery Demo</title>
</head>
<body>
<main>
<div id="world">
  <div id="nyc" class="city">
    <span class="citylink">NYC</span>
    <div class="details">
      <p><strong>New York City</strong>
      <br>Area: 1,213.37 km<sup>2</sup>
      <br>Population: 8,175,133
      <br>Source:
      <a href="https://en.wikipedia.org/wiki/New_York_City">
      Wikipedia</a></p>
    </div>
  </div>
  <div id="lon" class="city">
    <span class="citylink">LON</span>
    <div class="details">
      <p><strong>London</strong>
      <br>Area: 1,572.00 km<sup>2</sup>
      <br>Population: 9,126,366
      <br>Source:
      <a href="https://en.wikipedia.org/wiki/London">
      Wikipedia</a></p>
    </div>
  </div>
</div>
<script>
  //ready handler: run this code after the DOM is loaded.
  $(function() {
    $('.city').hover(
      //when the user's mouse enters any .city div..
      function() {
        $(this).stop(true);
        $(this).find('.details').show();
        //change the width and height (bigger),
        //over 1000 milliseconds,
        //and show the contained .elements div
        $(this).animate({
          'width': '260px',
          'height': '115px'
        },
        1000);
      },
      //when the user's mouse leaves any .city div.
      function() {
        $(this).stop(true);
        //change the width and height back to original values,
        //over 1000 milliseconds,
        //and hide the contained .elements div
        $(this).animate({
          'width': '40px',
          'height': '26px'
        },
        1000,
        function() {
          $(this).find('.details').hide();
        });
      }
    );
  });
</script>
</main>
</body>
</html>

Notice the following:

  1. We use a div of class city to mark up each city's info.
  2. Each div is positioned absolutely and is initially 40px wide by 26px high.
  3. We wrap our jQuery code in a ready handler to ensure that it runs after the page's DOM has loaded.
  4. We use jQuery's hover event to attach a handler to any element of class city.
    1. The first function contained within hover states what happens when the user mouses into the element.
    2. The second function states what happens when the user mouses out of the element.
  5. When the user's mouse enters, we change the width and height of the appropriate div with jQuery's animate method, making the div bigger over the course of 1000 milliseconds, and show the div of class details. Similarly, we animate the div back to its smaller size and hide the div of class details when the user mouses out.
  6. Again, please do not worry about the specifics of the code here; we will cover all of it in detail as we move through the course. Hopefully, you see the power of jQuery: how easy it is with just a few lines of code to produce complex, interesting effects and interactions.