In the previous exercise we learned how to use two arrays to display a group of pictures and text inside of an html document. In this exercise we are going to use a very similar technique that uses the same arrays to produce a slideshow that displays information for just one player at a time.
- Much of the work for this lesson was already taken care of in the previous lesson, so we might as well take advantage of it. So duplicate your work and move it into a new folder (maybe a Week Five folder).
- Open up the new folder in VS Code, and open roster.html and roster.js side by side.
- Comment out the ordered list in roster.html. Add a div and two buttons:
<div id="slideshow"></div> <button id="previous">Previous</button> <button id="next">Next</button>
- In roster.js, comment out or delete everything after the arrays. Create a variable named output and connect it to #slideshow. Also, let’s go ahead and establish a starting point by declaring a currentIndex variable. This variable holds our spot in the array.
let slideshow = document.querySelector('#slideshow');
let currentIndex = 0; - Create a function to display the current player.
function showCurrentPlayer() { slideshow.innerHTML = rosterNames[currentIndex] + "<br><img src='roster/" + rosterPix[currentIndex] + "'>"; }
- Now, we’re going to create a function that updates the index. Let’s call the function
canShow(plusMinus).function canShow(plusMinus) {
currentIndex = currentIndex + plusMinus;
// Keep the index within bounds
if (currentIndex < 0) {
currentIndex = 0;
}
if (currentIndex >= rosterNames.length) {
currentIndex = rosterNames.length - 1;
}
showCurrentPlayer();
} - Next let’s have the current player appear as soon as the page loads by adding this after the closing bracket of the canShow function.
showCurrentPlayer();
- It’s time to talk to the buttons. Let’s connect the next button first.
document.querySelector('#next').onclick = function () { canShow(1); }
- Try connecting the previous button on your own.
- Voila! You should have a functioning slideshow.
Come back here for a hint when you need it!
document.querySelector('#previous').onclick = function () {
canShow(-1);
}
How can I make the slideshow loop?
Change the for loop!
function canShow(plusMinus) {
currentIndex = currentIndex + plusMinus;
// Loop back to the end if too far left
if (currentIndex < 0) {
currentIndex = rosterNames.length - 1;
}
// Loop to the start if too far right
if (currentIndex >= rosterNames.length) {
currentIndex = 0;
}
showCurrentPlayer();
}