Creating an Autoplay Carousel with HTML, CSS, and JavaScript: A Comprehensive Guide

Faraz

By Faraz -

Learn how to create a captivating autoplay carousel using HTML, CSS, and JavaScript. Elevate your web design with interactive elements.


Creating an Autoplay Carousel with HTML, CSS, and JavaScript A Comprehensive Guide.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Welcome to our tutorial on creating a dynamic autoplay carousel using HTML, CSS, and JavaScript. In the ever-evolving landscape of web design, interactivity is key to capturing user interest. In this guide, we'll navigate through the essential steps, providing you with the skills to seamlessly integrate an autoplay carousel into your web projects. Get ready to elevate your design game and engage your audience with a captivating user experience!

Let's start making an autoplay carousel using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our carousel.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used.

2. <html lang="en">: The root element of the HTML document, indicating that the document is written in English (en stands for English).

3. <head>: This section contains meta-information about the HTML document, such as the character set, viewport settings, and the title of the webpage.

  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties to ensure proper rendering on different devices.
  • <title>Autoplay Carousel</title>: Sets the title of the webpage, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="style.css">: Links an external stylesheet (CSS file) named "style.css" to apply styles to the HTML content.

4. <body>: The main content of the webpage is contained within this element.

5. <div class="content">: This is the main container for the carousel content.

6. <div class="pagination">: Placeholder for pagination controls (not implemented in the provided code).

7. <div class="state"> </div>: Placeholder for some state information (currently represented by a non-breaking space  ).

8. <div class="controls">: Container for carousel control buttons.

  • <button class="control control--prev" aria-label="Previous">: Button for moving to the previous carousel item. It includes an SVG icon (an arrow pointing left).
  • <button class="control control--play-pause" aria-label="Play/Pause">: Button for toggling between play and pause states. It includes SVG icons for both play and pause.
  • <button class="control control--next" aria-label="Next">: Button for moving to the next carousel item. It includes an SVG icon (an arrow pointing right).

9. <script src="script.js"></script>: Links an external JavaScript file named "script.js" to the HTML document. This file contains the logic for the carousel, handling autoplay and user interactions.

This is the basic structure of our autoplay carousel using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the carousel is in place, the next step is to add styling to the carousel using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our carousel. Let's break down the CSS code step by step:

1. * selector:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

This selector applies the specified styles (setting padding, margin, and box-sizing) to all elements on the page. The box-sizing: border-box; property ensures that padding and border are included in the element's total width and height.

2. body selector:

body {
  background: #98ede0;
  transition: background 500ms;
  font-family: ui-rounded, "Hiragino Maru Gothic ProN", Quicksand, Comfortaa, Manjari, 
"Arial Rounded MT", "Arial Rounded MT Bold", Calibri, source-sans-pro, sans-serif;
}

This sets the background color of the entire page to a light teal (#98ede0). It also applies a transition effect to smoothly change the background color for 500 milliseconds. The font-family property sets the preferred font family for text on the page.

3. .content class:

.content {
  margin: 0 auto;
  max-width: 500px;
  height: 100vh;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  padding: 40px 40px 80px;
  justify-content: center;
}

This class styles a content container. It centers the container horizontally (margin: 0 auto;), sets a maximum width of 500 pixels, a minimum height of 400 pixels, and a height of 100% of the viewport height (height: 100vh;). It uses flexbox to arrange its children in a column, with additional padding and centering.

4. .pagination class:

.pagination {
  display: flex;
  gap: 10px;
  height: 4px;
  min-height: 4px;
}

This class styles a pagination container. It uses flexbox to arrange its children in a row with a gap of 10 pixels. The container has a fixed height of 4 pixels, which can be increased but not less than 4 pixels.

5. .pagination-item class:

.pagination-item {
  border-radius: 100px;
  height: 100%;
  flex: auto;
  background: rgba(0, 0, 0, 0.08);
  overflow: hidden;
  border: 0;
  cursor: pointer;
}

This class styles individual pagination items. They have a rounded appearance (border-radius: 100px;), occupy the full height of their container (height: 100%;), and have a background color with some transparency.

6. @keyframes progress:

@keyframes progress {
  from {
    width: 0;
  }
to { width: 100%; }}

This defines a keyframe animation named progress which animates the width of an element from 0% to 100%. It is later used for the progress bar in the pagination.

7. .pagination-progress class:

.pagination-progress {
  flex: auto;
  background: #333;
  height: 100%;
  width: 0;
}

This class styles the progress bar within the pagination. It has a dark background color, takes up the full height of its container, and initially has a width of 0.

8. Animation and state-related classes:

  • .pagination-item--running .pagination-progress: This applies the progress animation when a pagination item is in the "running" state.
  • .pagination-item--done .pagination-progress: Sets the progress bar width to 100% when a pagination item is in the "done" state.
  • .pagination--paused .pagination-progress: Pauses the progress animation when the pagination is in the "paused" state.
  • :-moz-window-inactive .pagination-progress: Pauses the progress animation when the browser window is inactive.

9. .controls and .control classes:

.controls {
  display: flex;
  justify-content: center;
  gap: 12px;
}
.control { /* ... */ }

These classes style a control container and individual control buttons, respectively. Controls are arranged in a row with a gap, and individual controls have a circular appearance.

10. .icon and .icon--play classes:

.icon {
  width: 20px;
}
.icon--play {
  margin-right: -2px;
}

These classes define the size of icons and adjust the margin of the play icon.

11. Conditional display of play/pause icons:

.pagination--paused ~ .controls .icon--pause,
.pagination:not(.pagination--paused) ~ .controls .icon--play {
  display: none;
}

This rule controls the display of play and pause icons based on the pagination state.

12. .state class:

.state {
  font-size: 120px;
  text-align: center;
}

This class styles a large text element with a font size of 120 pixels and centers the text.

This will give our carousel an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  background: #98ede0;
  transition: background 500ms;
  font-family: ui-rounded, "Hiragino Maru Gothic ProN", Quicksand, Comfortaa, Manjari, "Arial Rounded MT", "Arial Rounded MT Bold", Calibri, source-sans-pro, sans-serif;
}

.content {
  margin: 0 auto;
  max-width: 500px;
  height: 100vh;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  padding: 40px 40px 80px;
  justify-content: center;
}

.pagination {
  display: flex;
  gap: 10px;
  height: 4px;
  min-height: 4px;
}

.pagination-item {
  border-radius: 100px;
  height: 100%;
  flex: auto;
  background: rgba(0, 0, 0, 0.08);
  overflow: hidden;
  border: 0;
  cursor: pointer;
}

@keyframes progress {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
.pagination-progress {
  flex: auto;
  background: #333;
  height: 100%;
  width: 0;
}
.pagination-item--running .pagination-progress {
  animation: progress 3s linear forwards;
}
.pagination-item--done .pagination-progress {
  width: 100%;
}
.pagination--paused .pagination-progress {
  animation-play-state: paused;
}
:-moz-window-inactive .pagination-progress {
  animation-play-state: paused;
}

.controls {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.control {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 100px;
  border: none;
  outline: none;
  height: 40px;
  flex: 40px 0 0;
  max-width: 100px;
  background: rgba(255, 255, 255, 0.3);
  transition: transform 200ms, background-color 200ms;
  will-change: transform, background-color;
  font-size: 20px;
}
.control:hover {
  cursor: pointer;
  transform: scale(1.15);
  background: rgba(255, 255, 255, 0.45);
}
.control:focus {
  background: rgba(255, 255, 255, 0.6);
}

.icon {
  width: 20px;
}

.icon--play {
  margin-right: -2px;
}

.pagination--paused ~ .controls .icon--pause,
.pagination:not(.pagination--paused) ~ .controls .icon--play {
  display: none;
}

.state {
  font-size: 120px;
  text-align: center;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. This JavaScript code is for creating a simple pagination component with play/pause functionality and animated transitions between pages. Let's break down the code step by step:

1. Strict Mode:

"use strict";
  • This enables strict mode in JavaScript, which helps catch common coding mistakes and prevents the use of certain error-prone features.

2. getItem Function:

function getItem(index) {
    const item = document.createElement('button');
    item.classList.add('pagination-item');
    item.addEventListener('animationend', next);
    item.addEventListener('click', () => update(index));
    const progress = document.createElement('div');
    progress.classList.add('pagination-progress');
    item.appendChild(progress);
    return item;
}
  • This function creates a button element (item) for a pagination item.
  • It adds a 'pagination-item' class to the button.
  • It sets up event listeners for the 'animationend' event (calling the next function) and the 'click' event (calling an anonymous function that calls an update with the current index).
  • It also creates a child div (progress) with a class of 'pagination-progress' and appends it to the button before returning the button element.

3. createItems Function:

function createItems(itemsCount) {
    const items = [];
    for (let i = 0; i < itemsCount; i++) {
        items.push(getItem(i));
    }
    return items;
}
  • This function generates an array of pagination items using the getItem function based on the specified itemsCount.

4. jumpTo Function:

function jumpTo(item) {
    // ... (see the code for details)
}
  • This function is responsible for managing the visual state of the pagination items when jumping to a specific item. It adds or removes classes based on whether the pagination is paused or running.

5. update Function:

function update(index) {
    // ... (see the code for details)
}
  • This function updates the active index, jumps to the corresponding pagination item, updates the displayed state, and changes the background color.

6. prev and next Functions:

function prev() {
    // ... (see the code for details)
}

function next() {
    // ... (see the code for details)
}
  • These functions navigate to the previous and next pagination items, respectively, updating the active index and calling the update function.

7. playPause Function:

function playPause() {
    // ... (see the code for details)
}
  • This function toggles the paused state, updates the class of the pagination container, and, if unpausing and the current item is done, moves to the next item.

8. Constants and Initialization:

const colors = ['#98ede0', '#74b9ff', '#a29bfe', '#fd79a8', '#ffeaa7'];
const classNames = {
    RUNNING: 'pagination-item--running',
    DONE: 'pagination-item--done',
    PAUSED: 'pagination--paused',
};
let activeIndex = 0;
let isPaused = false;
const ITEMS_COUNT = 5;
const items = createItems(ITEMS_COUNT);
const $pagination = document.querySelector('.pagination');
const $state = document.querySelector('.state');
const $prev = document.querySelector('.control--prev');
const $next = document.querySelector('.control--next');
const $playPause = document.querySelector('.control--play-pause');
$pagination.replaceChildren(...items);
$prev.addEventListener('click', prev);
$next.addEventListener('click', next);
$playPause.addEventListener('click', playPause);
update(activeIndex);
  • Constants for colors and class names.
  • Variables for the active index and paused state.
  • The number of items (pagination pages).
  • Creating pagination items and initializing DOM elements.
  • Event listeners for previous, next, and play/pause controls.
  • Initial update with the active index.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

"use strict";
function getItem(index) {
    const item = document.createElement('button');
    item.classList.add('pagination-item');
    item.addEventListener('animationend', next);
    item.addEventListener('click', () => update(index));
    const progress = document.createElement('div');
    progress.classList.add('pagination-progress');
    item.appendChild(progress);
    return item;
}
function createItems(itemsCount) {
    const items = [];
    for (let i = 0; i < itemsCount; i++) {
        items.push(getItem(i));
    }
    return items;
}
function jumpTo(item) {
    if (isPaused) {
        item.classList.remove(classNames.RUNNING);
        item.classList.add(classNames.DONE);
    }
    else {
        item.classList.add(classNames.RUNNING);
        item.classList.remove(classNames.DONE);
    }
    let sibling = item;
    while ((sibling = sibling.previousSibling)) {
        sibling.classList.remove(classNames.RUNNING);
        sibling.classList.add(classNames.DONE);
    }
    sibling = item;
    while ((sibling = sibling.nextSibling)) {
        sibling.classList.remove(classNames.RUNNING, classNames.DONE);
    }
}
function update(index) {
    activeIndex = index;
    jumpTo(items[activeIndex]);
    // Update slide and background color
    $state.innerHTML = activeIndex + 1;
    document.body.style.backgroundColor = colors[activeIndex];
}
function prev() {
    if (activeIndex > 0) {
        update(activeIndex - 1);
    }
}
function next() {
    if (activeIndex < ITEMS_COUNT - 1) {
        update(activeIndex + 1);
    }
}
function playPause() {
    $pagination.classList.toggle(classNames.PAUSED);
    isPaused = !isPaused;
    // When unpausing,
    // if the current slide is done, jump to the next one
    if (!isPaused && items[activeIndex].classList.contains(classNames.DONE)) {
        next();
    }
}
const colors = ['#98ede0', '#74b9ff', '#a29bfe', '#fd79a8', '#ffeaa7'];
const classNames = {
    RUNNING: 'pagination-item--running',
    DONE: 'pagination-item--done',
    PAUSED: 'pagination--paused',
};
let activeIndex = 0;
let isPaused = false;
const ITEMS_COUNT = 5;
const items = createItems(ITEMS_COUNT);
const $pagination = document.querySelector('.pagination');
const $state = document.querySelector('.state');
const $prev = document.querySelector('.control--prev');
const $next = document.querySelector('.control--next');
const $playPause = document.querySelector('.control--play-pause');
$pagination.replaceChildren(...items);
$prev.addEventListener('click', prev);
$next.addEventListener('click', next);
$playPause.addEventListener('click', playPause);
update(activeIndex);

Final Output:

Creating an Autoplay Carousel with HTML, CSS, and JavaScript A Comprehensive Guide.gif

Conclusion:

Congratulations! You've successfully created an autoplay carousel using HTML, CSS, and JavaScript. Experiment with customization to suit your project's unique needs. Elevate your web design and captivate your audience with dynamic, interactive carousels.

Code by: Stanko

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post