We will be using JQuery for the rest of the workshop, but before we learn JQuery, we must know what a code library is.
Understanding Code Libraries
We've learned several functions built into JavaScript, including log, getElementById, and getElementsByTagName. Despite there being many other functions built into JavaScript, there aren't nearly enough to satisfy all situations.
Developers can extend the functionality of JavaScript with their own custom code. These bundles of custom 3rd-party code that extend the functionality of JavaScript are called libraries.
There are many libraries available on the web to download for a variety of purposes. For example, there are certainly many libraries that specifically make creating JavaScript slide shows easier.
For most common tasks in JavaScript, there is a good chance you will be able to find a relevant JavaScript library to assist you. When you don't have to reinvent the wheel, it's usually better not to.
NOTE: It is important to recognize that JavaScript libraries are written in JavaScript, and usually take the form of a JavaScript file or collection of JavaScript files.
Understanding the Purpose of JQuery
JQuery is by far the most popular JavaScript library. Interestingly, unlike most JavaScript libraries, JQuery doesn't offer any specific solution. Instead, JQuery is simply designed to make manipulating the DOM much easier across the board.
With JQuery, referencing, modifying, and creating elements is significantly easier. It is also much easier to add interactivity to your page.
One of the best features of JQuery is that it is free to use and that it has an excellent web site that is full of documentation and examples concerning the capabilities of the library. You can download JQuery and find these resources at the following address:
http://www.jquery.com
Loading JQuery into the Document
In order to begin using JQuery, we have to load it into our document.
The entirety of JQuery exists in a single JavaScript file. We can access it by either downloading it to our project directory and creating a link for it in our HTML file, or we can simply create a link directly from our HTML file to the web address that stores the JQuery file.
The advantage of downloading the JQuery file is that you can test your page while you are not connected to the Internet, as well as the added security of not having to rely on the external web site that hosts the JQuery file being up.
The advantage of linking directly to the web address within the HTML file is that you don't have to go through the effort of downloading the file to your project directory. In addition, users who visit your site won't be using your server's bandwidth to download the JQuery file.
To make this process easier, we have included the line of code you need to add to your HTML file in order to add JQuery functionality to your page. This code is sitting inside of jquery.txt, which is in your project folder. We can copy its contents and paste it into our HTML file.
Step 1. Open jquery.txt in the JavaScript Basics project folder.
Step 2. Select all the text in the jquery.txt text file.
Step 3. Copy the selected text.
Step 4. Close jquery.txt.
Step 5. Switch back to the code editor with programming_basics.html.
Step 6. To access JQuery in our project document, paste the line of code in the <head> element:
<head>
<meta charset="UTF-8" />
<title>Programming: The Basics</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/JavaScript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
Exiting code block
NOTE: The <script> element appears on multiple lines in this document because the line wrapped on the page. It is actually only on one line in the code. We typically keep the closing </script> tag on the same line here because we don't write any code in the <script> element that loads JQuery. We will discuss this later in the workshop.
Introducing $, the JQuery Function
JavaScript libraries typically add a variety of functions, and usually expect a specific HTML structure and set of element attributes in order to function properly.
JQuery is peculiar in that it effectively stems from of a single function, the JQuery function, and that it can be used on any HTML structure.
The JQuery function has an alias, which means that there is another way to refer to it. The JQuery alias is simply the dollar symbol ($()), which is far more commonly used than actually writing out "JQuery()" when calling the function.
We learned previously that JQuery is used in order to make selecting and modifying elements in the DOM easier. The way JQuery does this is through the use of CSS selector syntax. You can reference a node in the DOM by supplying a CSS selector as the argument to the $() function. The syntax looks like this:
$(cssSelector)
Exiting code block
With this, we no longer have to use getElementById or getElementByTagName in order to access our DOM nodes.
NOTE: The object that the $() function retrieves is not the same as what the getElementById function retrieves. The $() function retrieves a special JQuery-specific representation of the node that has special JQuery functionality built-in. We will learn more about this throughout the workshop.
Modifying Multiple Nodes Simultaneously
Earlier, we decided we wanted the ability to modify multiple nodes at once. We can do this using either plain JavaScript or JQuery. In order to paint the contrast between using plain JavaScript and JQuery, let's take a look at how we would achieve this with both solutions.
Let's say that we want to make all of our <h2> elements gray. In plain JavaScript, we would write something like this:
var allh2 = document.getElementsByTagName("h2");
for (var i = 0; i < allh2.length; i++) {
allh2.style.color = "gray";
}
Exiting code block
Don't worry about foreign structures in the previous code; we will get to these concepts later in the workshop.
The JQuery functional equivalent to the above plain JavaScript code looks like this:
$("h2").css("color", "gray");
Exiting code block
As you can see, this is far shorter and far more intuitive. The $() function retrieves all <h2> elements, using the <h2> CSS selector, and then applies the value "gray" to the CSS color property by using the JQuery node's built-in css function.
Let's say we actually do want our <h2> elements to be gray, so let's type this into our script now.
Step 1. To change the color of all <h2> elements, at the bottom of the document, type:
<script>
// Turn all <h2> nodes gray
$("h2").css("color", "gray");
// Turn all <h2> nodes gray
// Hide all slides
// Show the first slide
// Go to the next slide
// Go to the previous slide
// Create slide-to-slide jump navigation
// Create slide numbers
/* this was practice code
Exiting code block
Step 2. Save the document and reload it in the web browser.
Manipulating Visibility of Element Nodes
A common task for JavaScript and JQuery is to change the visibility of various elements on the page from hidden to visible and from visible to hidden, depending on the circumstance. With JQuery, this is very simple.
Hiding Element Nodes
To hide a node, we simply call the hide() function on a node we retrieve using the $() function. No arguments are necessary for this function.
In our case, a problem we are having with our page is that all slides are visible when the page loads. We only want to see one page at a time. To fix this, we will first hide all our slides.
Step 1. To hide all the slides in the slide show, on an empty line of the <script>element, type:
// Hide all slides
$(".slideshow section").hide();
Exiting code block
Step 2. Save programming_basics.html and reload it in the web browser.
Making Element Nodes Visible
After we hide all the sections when the page loads, we want to show the first slide. The first slide uses the class attribute value of slide0, so we will use that as the selector. We can make this slide visible again by using the show function, which works in the same way as the hide() function we just used.
Step 1. To show the first slide of the slide show, type:
// Turn all <h2> nodes gray
$("h2").css("color", "gray");
// Hide all slides
$(".slideshow section").hide();
// Show the first slide
$(".slide0").show();
Exiting code block
Step 2. Save the document and reload it in the web browser.
NOTE: The show() and hide() functions can take an optional numeric argument which represents the number of milliseconds you want the selected node to take transitioning toward being visible or invisible.
Managing Visible Slides
We want to add the functionality to allow the visitor to change slides. In order to do this, we have to lay down the groundwork for managing which slide is visible.
Keeping Track of the Active Slide
In order to better keep track of which slide is visible, it would be useful to create a variable that remembers the number of the active slide.
Let's create a variable called currentSlide with an initial value of 0. This must be the first thing that our script executes so that the variable exists before we could possibly do anything with it. If we tried to use a non-existent variable, JavaScript would give us an undefined variable error.
We also must give this variable an initial value of 0 to match the index of our first slide, otherwise, JavaScript will interpret the value of the variable to be 'undefined'.
Let's create our currentSlide variable and assign it an initial value of 0 now.
Step 1. To create a variable for remembering the current page, on a new line immediately after the opening <script> tag, type:
<script>
var currentSlide = 0;
// Turn all <h2> nodes gray
Exiting code block
Showing the Next Slide
Whenever we need to change which slide is visible, we know that we can hide all slides and show the one we want. We also want to make sure that we update the currentSlide variable so that we can more easily refer to which slide we are on, so that we know which slide to go to next.
If we want to go up a slide, then we'll also use the increment operator on the currentSlide variable.
Step 1. To increment the currentSlide number, type:
// Hide all slides
$(".slideshow section").hide();
// Show the first slide
$(".slide0").show();
// Go to the next slide
currentSlide++;
Exiting code block
Step 2. To hide all slides and show the next slide, type:
// Go to the next slide
currentSlide++;
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
Exiting code block
Step 3. Save the document and reload it in the web browser.
Introducing Functions
The code where we hide all the slides and show the current desired slide will need to be executed every time the visitor wants to change slides.
Whenever a particular block of code needs to be used more than once, it is usually a good idea to define a custom function for that block of code. This way, we can just call the function whenever we want that code to be run.
Custom functions that we define work just the same way as ones that are built in. The only difference is that we have to define it ourselves.
Defining a Function
We are going to create a new function to include the statements that hide all the slides and show the current slide.
The syntax for creating a function include using the function keyword followed by the name we want to give the function, much like how we use the var keyword to define variables. However, in addition to giving the function a name, we have to use a set of parentheses to specify how many arguments the function will expect, as well as a pair of braces ( { } ) that surround the statements we want to execute when the function is called.
The syntax for defining a function looks something like this:
function my_function() {
statements to execute;
}
Exiting code block
Let's try this out by creating a function that includes the two statements that hide all the slides and show the current slide.
Step 1. To define the function, type:
// Go to the next slide
currentSlide++;
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
}
Exiting code block
NOTE: Notice the indentation here. This is simply to organize our code and make it easier for us to see what belongs to which code block. JavaScript ignores this sort of indentation.
Step 2. Save the document and reload it in the web browser.
NOTE: Our show_current_slide function does not need any arguments in order for it to run, so we left the parentheses in the function definition empty. In fact, we do not plan to create any functions that do take arguments. If you are interested in creating a function that takes arguments, then research creating parameters in programming. Parameters are the name used to describe arguments in the function definition.
Calling Your Function
Now that our code is inside a function definition, it will not automatically execute when we load the HTML page. It will only run when we explicitly call the function in the code.
Calling a custom-made function has exactly the same syntax as calling a function built into the language by default.
Let's call show_current_slide where we used to execute the statements that are now in the function definition.
Step 1. To call the new function, on a blank line immediately after the currentSlide++ statement, type:
// Go to the next slide
currentSlide++;
show_current_slide();
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
}
Exiting code block
Step 2. Save the document and reload it in the web browser.
NOTE: We can call the function before or after the function definition code. This is because the browser first loads all the function definitions in memory before running the code.
Introducing JQuery Events
Thus far in the workshop, we haven't added any interactivity to our web page, that is, the user of the page does not have any power to change slides or much of anything.
In JavaScript and JQuery, we can add interactivity through a concept called events. An event entails programming the page to expect some kind of predefined scenario to happen, at which point a custom set of actions will be performed.
A predominant form of event is one that "listens" for a mouse click. This is what we will try next.
Using Click Events
In JQuery, we can tell the page that when the desired node is clicked, execute a series of statements. We can do this with the click event, which takes the form of a function that belongs to a JQuery node object that we match with the $() function.
Let's say that we want the paragraph whose text says "Next Slide" and whose class is ".nextSlide" to show the next slide once it is clicked.
We know that the code that will go to the next slide is a combination of incrementing the currentSlide variable and calling the show_current_slide function. We will wrap these statements in the click function being called from the object received from the $() function matching the node that possesses the class "nextSlide".
Step 1. To create an event that triggers with mouse click, type:
// Go to the next slide
$(".nextSlide").click ( // Next Slide Click Event
currentSlide++;
show_current_slide();
);
Exiting code block
Using Anonymous Functions
The click event function expects a function as its argument—not a series of statements. As a general rule, statements must be either on the root level of the script or within a pair of braces, which are referred to as a code block.
We can either define a new function with our statements and then supply the new function's name as the argument to the click event function, or we can use an anonymous function.
An anonymous function is simply a custom function that we don't give a name. These are generally used whenever the function will only be called in one specific context. In this case, these statements will only be used when the click function is triggered, therefore an anonymous function is the typical choice.
Step 1. To create the anonymous function, type:
// Go to the next slide
$(".nextSlide").click (function() { // Next Slide Click Event
currentSlide++;
show_current_slide();
});
Exiting code block
NOTE: Make sure that you type the anonymous function's closing braces before the closing parenthesis for the click function.
Step 2. Save the document and reload it in the web browser.
Step 3. To reveal the second slide, at the top of the page,
Click Next Slide
Step 4. To reveal the third slide,
Click Next Slide
NOTE: We aren't using any other types of events in this workshop, but there are many other events available in JQuery. A few examples include the hover event for when a mouse hovers over the selected node, the scroll event for when the visitor scrolls the page, and the ready event which is triggered as soon as the page loads (allowing you to put your code at the top of the page while still accessing the DOM tree).
Challenge Exercise/On Your Own: Create Previous Slide Functionality
The next slide functionality works. Now it's your turn to take what you've learned to make the previous slide functionality work. Create a click event for the "Previous Slide" paragraph, the same way you did for the "Next Slide" paragraph.
Step 1. Duplicate the click event code on a separate blank area of the <script> element.
Step 2. Change the JQuery selector to target the "prevSlide" class.
Step 3. Change the currentSlide increment operator (++) to the decrement operator (--).