Check out a free preview of the full Using JavaScript in Websites course

The "Previous Button" Lesson is part of the full, Using JavaScript in Websites course featured in this preview video. Here's what you'd learn in this lesson:

Brian codes the previous button to work similarly to the next button, going in the opposite direction.

Preview
Close

Transcript from the "Previous Button" Lesson

[00:00:00]
>> Brian Holt: I think it makes sense that we should go back and do previous then right? As you might imagine, it's pretty much the opposite, right? You do pretty much the same set of steps. It's just gonna be almost the opposite.
>> Brian Holt: So this line right here, line 12 literally gonna be the same.

[00:00:20]
>> Brian Holt: GalleryImgs[currentlySelected].classList.remove("active");.
>> Brian Holt: Right, because if you're going previous in the list, then you still have to hide the current image.
>> Brian Holt: And then here, currently select instead of going forward we're gonna go backwards, so if I'm on image one and I wanna go back to zero, I have to do current image minus minus, right?

[00:00:53]
And again, that's the same as currentlySelected = currentlySelected- 1. Let's make that a comment.
>> Brian Holt: Okay.
>> Brian Holt: And then I do the same step here, galleryImgs[currentlySelected].classList.add("active");.
>> Brian Holt: Then we're gonna say the nextBtn.
>> Brian Holt: .Disabled is gonna be assigned false.
>> Brian Holt: Okay.
>> Brian Holt: Now when do we stop going previous?

[00:01:47]
At what point do we have no more previous images to show? What is currently selected?
>> Speaker 2: The first one.
>> Brian Holt: Which is index what? What is currently selected going to equal at that point?
>> Speaker 2: Zero.
>> Brian Holt: Yeah, so you're both right. That zero one, is the first one.

[00:02:06]
>> Speaker 2: Is the first yeah.
>> Brian Holt: Yeah, exactly, you got it. So if currently selected, === 0 then prevBtn, is that right, yep, disabled = true.
>> Brian Holt: So as you can see, the logic here is almost exactly the same. The only thing that changes here is we're going backwards instead of going forwards and then which buttons were enabling and disabling.

[00:02:42]
Otherwise it's 100% the same logic.
>> Brian Holt: Okay, so now, I have
>> Brian Holt: Luna here and if I hit next, and I hit previous again, it does go back. It does disable previous, does everything that we're supposed to do.
>> Brian Holt: Yeah?
>> Speaker 3: I'm using the code form the course website.

[00:03:06]
In the init function, does it matter the order that you put your functions in?
>> Brian Holt: Nope. As long as they both get called, yeah, it doesn't matter.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now