Now that we have our Next and Previous Slide links working, we may notice that a problem we are running into is that the Previous Slide link shows up even if there is no previous slide, and the Next Slide link remains, even on the last slide.
To get started with solving this problem, let's take a look at how to allow our script to make decisions.
Introducing Conditional Expressions and Booleans
We have already learned that an expression is any piece of code that represents a value. A conditional expression is just any expression whose value is either true or false. There is a specific data type whose values are entirely limited to true or false, and that is the boolean. This will be paramount for us to be able to add complex functionality into our page, because conditions are the foundation for computer logic, that is, having the program make decisions depending on particular scenarios.
Booleans, along with numbers and strings, make up the entire list of primitive data types, that is, values that are so basic that they are not even objects in JavaScript. For example, you cannot use the dot operator on a number, because a number does not possess any properties or methods; it is just a number.
Understanding Comparison Operators
Comparison operators compare two values and return a boolean value and are used exclusively within conditional expressions. They include less than (<), greater than (>), equals (==), less than or equal (<=), greater than or equal (>=), and not (!). When we use these operators, we will yield a true or false value.
Let's test them out back in the Console window of our browser.
Step 1. Switch to the Console window in the web browser.
Step 2. In the Console prompt, type:
1 == 1, press: Enter
Step 3. In the Console prompt, type:
1 == 2, press: Enter
Step 4. In the Console prompt, type:
1 < 2, press: Enter
Step 5. In the Console prompt, type:
1 != 2, press: Enter
Step 6. In the Console prompt, type:
1 == "1", press: Enter
NOTE: Keep in mind that the equals operator uses two equal signs and not one. The assignment operator uses a single equal sign. If you accidentally use the assignment operator in place of the equals operator, you will most certainly have unpredictable behavior on your page.
Using the If Statement
So far in our project, the code will always be executed the same way, no matter the scenario. For example, the same statements run when the page loads, and the same sequence of statements run each time the Previous or Next Slide links are clicked.
If we want more complex functionality in our page, we will have to add conditions that trigger different code depending on the scenario. For example, we want the Previous Slide link to be visible conditionally with the appropriate slides, and the same goes for the Next Slide link.
We can accomplish more advanced logic with the concept of control structures. A control structure is one that executes code depending on specified conditions.
The first code structure we will be learning about is the if statement. The if statement allows us to execute a block of code, as long as our defined condition is met. The syntax looks like this:
if (condition) {
statements to execute;
}
Exiting code block
In our case, we want to solve the problem with the Previous Slide link either being visible when we don't want it to be or invisible when we want it to be visible. For example, we don't want the Previous Slide link to be visible on the first slide.
Before writing the rest of our code logic, it is often a good idea to first create a comment that describes the intent of the code that comes after it.
Step 1. To describe what we intend to achieve using a line comment, in the show_current_slide function type:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
//hide prevSlide link when on first slide
}
Exiting code block
Step 2. At the end of the show_current_slide function, type:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
//hide prevSlide link when on first slide
if (currentSlide == 0) {
}
}
Exiting code block
Step 3. To hide the Previous Slide link when currentSlide is 0, in between the curly brackets of our new if statement, type:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
//hide prevSlide link when on first slide
if (currentSlide == 0) {
$(".prevSlide").hide();
}
}
Exiting code block
Step 4. Save the document and reload it in the browser.
Step 5. To test if the if statement worked,
Click Next Slide
Step 6. To return to the first slide,
Click Previous Slide
Using an Else Branch
We've only partially solved the Previous Slide link visibility problem, but we still have the Next Slide link visibility problem, where the Next Slide link remains visible even on the final slide.
We can create another if statement to handle this case, but in most cases, it makes more sense to use an else branch of the same if statement. An else branch is triggered if the condition in the if statement is false.
To set up an else branch, simply type the keyword else after the closing brace for the if statement. You can either follow that with a pair of braces, if you want the else branch to always execute when the if statement condition is false; or you can type another if statement following the else keyword if you want to test another condition before executing a different set of statements.
In our case, after the interpreter deems that the page is not on the first slide, we want to then check if the page is on the last slide, which for us would be slide 3, that is, index 2.
Step 1. To create an else if block, type:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
//hide prevSlide link when on first slide
if (currentSlide == 0) {
$(".prevSlide").hide();
} else if (currentSlide == 2) {
$(".nextSlide").hide();
}
}
Exiting code block
Step 2. Save the document and reload it in the web browser.
Step 3. To test the visibility of the slide links,
Click Next Slide
Step 4. To continue testing the page,
Click Next Slide
Using Multiple JQuery Selectors
Just like with CSS, we can use JQuery to select multiple items at once. In fact, it uses exactly the same syntax as in CSS.
Let's make the Previous and Next Slide links behave .
Step 1. In the web browser, click the Previous Slide link.
Step 2. To reveal the Previous and Next Slide links when they are clicked, modify the show_current_slide function as shown:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
$(".prevSlide,.nextSlide").show();
//hide prevSlide link when on first slide
if (currentSlide == 0) {
$(".prevSlide").hide();
} else if (currentSlide == totalSlides - 1) {
$(".nextSlide").hide();
}
}
Exiting code block
Step 3. Save the document and reload it in the web browser.
Step 4. To check if the Previous Slide link will remain visible,
Click Next Slide
Step 5. To further test the page,
Click Previous Slide
Making the Code More Scalable
Our Previous and Next Slide links appear to be going visible or invisible at the correct times. However, if we added slides later, then our currentSlide == 2 condition would break this functionality, since there would be more than three pages.
Each time we would add or subtract slides, we would have to update that number. This is cumbersome at best, particularly if we have multiple pages that each have a different number of slides.
It is important for the developer to consider these kinds of situations, and to have the foresight to create code that remains flexible even when the project changes in a variety of ways. This is what is meant by scalable code.
Implementing a Total Slides Variable
A typical strategy for creating scalable code is to assign more loose values, which in programming are called literals, to variables. Not only does this give the developer a way to programmatically change the value when needed, but it better annotates the purpose behind a value that we are using.
Setting Up the Total Slides Variable
In order to better scale with the number of slides that may be in the slide show, let's create a variable that stores the number of slides that are on the page.
Step 1. To define the totalSlides variable, type:
<script>
var currentSlide = 0;
var totalSlides;
Exiting code block
Step 2. To assign a value to the totalSlides variable, type:
// Hide all slides
$(".slideshow section").hide();
// Show the first slide
$(".slide0").show();
totalSlides = $(".slideshow section").length;
Exiting code block
Step 3. To fix our Previous and Next Slide links behavior, make the edits shown below:
// Hide all slides
$(".slideshow section").hide();
// Show the first slide
show_current_slide();
totalSlides = $(".slideshow section").length;
Exiting code block
Step 4. Save the document.
Checking Against Total Slides
We are now ready to replace the literal value of 2 in our show_current_slide function with our totalSlides variable.
Keep in mind that we expect the totalSlides variable to have a value of 3, because there are three slides. But in our condition, we are looking for the value 2, because in zero-based numbering, that represents the third item. To handle this, we will subtract 1 from the totalSlides value when we are checking against the currentSlide.
Step 1. To make the show_current_slide function more scalable, modify it to reflect the code shown:
// Show the current slide
function show_current_slide() {
$(".slideshow section").hide();
$(".slide" + currentSlide).show();
$(".prevSlide,.nextSlide").show();
//hide prevSlide link when on first slide
if (currentSlide == 0) {
$(".prevSlide").hide();
} else if (currentSlide == totalSlides - 1) {
$(".nextSlide").hide();
}
}
Exiting code block
Step 2. Save the document and reload it in the browser.
Step 3. Verify the slides' navigation still works as intended.
NOTE: The expression in the else if conditional clause, currentSlide == totalSlides - 1, evaluates by first performing the arithmetic expression, totalSlides - 1, and then taking the value and comparing it against the currentSlide variable. In other words, currentSlide == totalSlides - 1 becomes currentSlide == 2 (in our case), which becomes either true or false, depending on the value of currentSlide.
Setting Up the Sidebar Links
Our Previous and Next Slide links work, but our sidebar navigation does not do anything yet. We want it so that when the visitor clicks on an item in the sidebar navigation list, the interpreter will show the appropriate slide. This won't be much different than setting up the events for the Previous and Next Slide links, but there are considerations to be made, such as scalability to sidebars that include many links.
Setting Events on Multiple Nodes Simultaneously
We successfully applied click events to single nodes at a time. It would be nice to be able to apply a single click event to a number of nodes simultaneously. In this case, we want the page to listen for a mouse click on any of the items in the sidebar navigation list.
This is easy to do in JQuery. We simply have to match all the relevant list items in a single $() function, and then apply the click event function to what is selected.
Let's create the shell for this click event function now.
Step 1. To add a click event to our sidebar links, within the <script> element, type:
// Create slide-to-slide jump navigation
$("nav li").click(function () {
});
// Create slide numbers
Exiting code block
Step 2. To plan the code that will make up the new click event, type:
// Create slide-to-slide jump navigation
$("nav li").click(function () {
//change currentSlide to match clicked list item
show_current_slide();
});
Exiting code block
Using the this Keyword
We want something different to happen depending on the list item that was clicked. For example, we want the first slide to show when the first list item is clicked, and we want the second slide to show when the second list item is clicked. However, as you can see, the exact same block of code will be run no matter which list item is clicked. There are a couple JQuery features that can help us here.
First of all, there is a JQuery function named index that gets the index of the specified item in an array of nodes. The selector nav li in our click event will match an array of nodes.
However, we have to tell JQuery which item of the array is being specified in order for the index function to work correctly. We can do this with the this keyword. The this keyword refers to the specific item that was triggered by the event within an array of nodes matched by the $() function that called the event.
To use JQuery's this keyword, you must include it, without quotes, as the argument in a $() function call. This will get the desired node. Then we will call the index function to get the position of the list item that was clicked within the navigation.
Step 1. To set currentSlide to reflect the index of the list item, type:
// Create slide-to-slide jump navigation
$("nav li").click(function () {
//change currentSlide to match clicked list item
currentSlide = $(this).index();
show_current_slide();
});
Exiting code block
Step 2. Save the document and reload it in the web browser.
Step 3. To test our click events, in the sidebar,
Click the among the three list items
NOTE: We can keep the line comment in place in order to describe the code underneath it, since the code's purpose might not be immediately obvious just by glancing at it.
Challenge Exercise 2: Testing Scalability
Let's test the scalability of our project. We have provided a snippet file that contains some code to place inside the <article> of the page.
Step 1. Paste the contents of the snippets.txt file inside the <article> after the .slide2 <section>.
Step 2. Modify the sidebar to include the new slide.
Step 3. Save and test the page.