Autoplay carousel js

Image courtesy the author

I was working on my personal portfolio and I wanted to make a slideshow for the photography page. My first inclination was to use a library, such as Bootstrap Carousel. While I love Semantic, I could not find a slideshow component/library. And while I would recommend Bootstrap, I decided to go with a simpler, home-grown slideshow. I wasn’t totally sure how I wanted it to look or function, but I did know that I wanted two things:

  1. Automatic run time [Change pictures every couple seconds automatically]
  2. Manual controls [So the user can go back/forward if they choose]

I had made my own slideshows before, but I had never made my own that works both automatically and has options to work manually. The issue I’ve had in the past is that, while you can set the slides to change at an interval on its own [automatic], whenever I introduced a manual operation [such as Next/Previous selection], the interval is maintained and doesn’t re-adjust to the manual operation.

This means if the automatic interval is set to four seconds — In new media, the recommended optimal time for pictures to change in a slideshow is, at minimum, three to four seconds — and the user decides to click Next after three seconds, the picture will change, but then one second later the picture changes again [automatically].

This isn’t conducive to the user experience. If they went back to a picture or wanted to see the next picture more than the current one, it’s safe to say they wanted to do so for more than a second. It makes sense to reset the interval, so they can see the next/previous picture for the same amount of time as the other pictures. I have actually run into this issue using libraries, and these libraries are often a bit harder to overwrite easily [lest you start throwing !importants everywhere].

So here is the slideshow I made that incorporates both automatic and manual functionality.

As you can see, the slideshow runs automatically, but should the user choose to go to the next/previous picture it does not disrupt the interval. So how did I achieve this? If you’ve read any of my previous pieces, you know exactly how I did this.

Magic!

OK while magic is 150% real, I did something different.

What I ended up doing was this: HTML.

I created a container, I centered it, and within that container [actually just a

], I put six child
s within it. Within those
s I put an and of course another
for the caption. It’s like the movie Inception, but with
s.

Here’s what the code looks like.

This code consists of the slideshow container, four slideshow images, and the Previous/Next arrows. But of course, the magic is in the JavaScript.

The function I will introduce first is plusSlides.

I’ll explain the initialization and clearInterval in a minute. But setInterval is the function I used because it essentially setTimeouts something at a repeated interval. You can setTimeout to execute the plus slides function, but then you’d have to repeat that function again. To avoid unnecessary redundancy, setInterval is just what you need. It sets the interval in which you determine a function to execute, and when/how often you want to execute it.

Essentially, this function initializes the slideshow as well as decide whether to go forward or backward within the sequence. And what determines the forward/backward functionality? The n that is passed into the function. If n is negative, the slideshow index selected will be the index prior to the current one. So if you are on the fourth picture [at index three], and you click the back arrow, you are selecting the slide at index as the current slide to be shown. If n is positive, you would go to the next index in the sequence. So if you’re on the slide at index two and you click next, you will bring up the next slide, at index three. This corresponds to another function I’ve written, called showSlides.

The function gathers the slide elements and the dots elements. These will be stored in arrays. The items in these arrays will be selected based on their relation to slideIndex. showSlides determines which slide to show and which slides to hide when you select next or previous, or if you let the slideshow run automatically. As you can see, there is on setInterval or clearInterval here. This function serves only to apply the appropriate CSS classes and styles given the current slide index. There were other code snippets online that did the same thing as showSlides, but the changing of classes was over complicated. I simplified class assignment process for the dots [which actually has significant style changes, like color and opacity], and simply changed the display to either block or none for the slides. I incorporated a loop to remove styles/classes from all slides/dots that are not found at the current index. Since the number of dots will correspond to the number of pictures, the slideIndex can be applied as the current index for slides as well as the dots.

Now it’s time to set everything in motion.

We initialize both myTimer and slideIndex. slideIndex is set to one [throughout the function we refer to the indexes as slideIndex-1]. myTimer will be assigned the interval that we will set for the slideshow. When the page loads, it first runs the showSlides[n] function, to determine which slide to show first. Then it reassigns myTimer a function and interval in which that function [plusSlides] should execute at a specific time [every 4,000 milliseconds].

But what about the dots? Are they simply an aesthetic choice?

Nope.

They also serve a functional purpose. Let's look at the HTML.

As you can see, each of the dots has an title function, called currentSlide. currentSlide takes an argument of number. What will this number represent?

You got it, slideIndex. Below is the currentSlide function.

This function serves to allow the user to select a specific picture in the slideshow. If you are on the first slide and want to see the third, rather than clicking Next or Previous twice, you can simply select the third dot. This will clear whatever interval is already in place so as not to create overlap between the previous interval and the new one. Once the interval is clear, it’s free to be reassigned at the convenience of the user. This happens with the reassignment of myTimer. This is important because the user should be able to select any dot at whatever point in the interval and not have the timing of the slides change. So if you’re three seconds into the third slide and want to go back to the first, you can click the first dot and reset the interval without causing any skipping of the slides. This executes the plusSlides[n+1] based on what dot is clicked.

On the next line, you can see we execute showSlides and reassign slideIndex to n, the index passed from the dot which will determine the slide at that index in our slides array to show. The function has now reassigned myTimer to coincide with the user’s new selection, as well as to show the slide at the index that corresponds to the selected dot.

In essence, what you have is a set of functions that set the interval, and also reset the interval if the user interacts manually. And setting the interval as well as the slide when it’s triggered by either the user clicking a button or simply by the timing of an interval allows for both manual control and automatic execution for our slideshow. This ensures continuity throughout the automatic and manual controls. And by allowing both, we give the user the option to interact and choose what they see or to just sit back and enjoy the [slide]show.

I have a CodePen, including the HTML, CSS, and JavaScript for this slideshow UI.

Medium reader Tony Pero commented on this piece about implementing Play/Pause functionality for when a user hovers over the slideshow. In response, I was able to implement it myself. To allow the user to pause the slideshow when they hover over the slideshow container, you need to add a mouseenter event listener. If you want the slideshow to resume when the user stops hovering over the slideshow container, you need to implement a mouseleave event listener. I added the below code at the end of my on load document event listener.

Here is my pause function.

As you can see, I use clearInterval to stop the timed interval of automatic slideshow switching. By hovering over the container, myTimer is cleared and the slideshow can only be moved by clicking the Previous/Next arrows or the circle indicators.

Next is my resume function. This will be executed when the user moves the mouse from over the slideshow container.

We use clearInterval again to account for other factors [such as interacting with arrows and indicators] that may create conflicts with the new interval. Immediately after clearInterval, we reset the value of myTimer to a new interval, execute the plusSlides function, and pass it the current slideIndex. This creates the illusion that the slideshow is picking up from where the user left off last, and the user’s experience is uninterrupted.

Video liên quan

Chủ Đề