Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Building a Carousel with Vanilla JavaScript
Next article icon

Building a Carousel with Vanilla JavaScript

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A carousel, also known as an image slider, is a popular web component that allows users to cycle through a series of images, texts, or other content. we'll walk you through creating a responsive carousel using Vanilla JavaScript, HTML, and CSS without relying on any external libraries.

What We Are Going to Create

  • Basic Carousel: Use HTML to structure the images and CSS for layout and responsiveness.
  • Navigation Buttons: Add "Previous" and "Next" buttons to manually move through images.
  • Auto Play: Implement JavaScript to automatically cycle through images at intervals.
  • Styling: Use CSS to enhance the appearance with borders, shadows, transitions, and ensure responsiveness.

Project Preview

Carousel Application - HTML & CSS Structure

The first step in building a carousel is to define its HTML & CSS structure. We'll need a container for the carousel, individual images, and navigation buttons for the user to move between the images.

HTML
<html> <head>     <style>         body {             font-family: Arial, sans-serif;             margin: 0;             padding: 0;             display: flex;             justify-content: center;             align-items: center;             height: 100vh;             background: #f4f4f4;         }         .car {             position: relative;             width: 80%;             max-width: 600px;             overflow: hidden;         }         .img-wrap {             display: flex;             transition: transform 0.5s ease;         }         .img-wrap img {             width: 100%;             height: auto;         }         .btn {             position: absolute;             top: 50%;             transform: translateY(-50%);             background: rgba(0, 0, 0, 0.5);             color: #fff;             border: none;             padding: 10px;             font-size: 16px;             cursor: pointer;         }         .btn:hover {             background: rgba(0, 0, 0, 0.8);         }         .prev {             left: 10px;         }         .next {             right: 10px;         }     </style> </head> <body>     <div class="car">         <div class="img-wrap">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20241228102812942963/0_ilw552fVUGbwIzbE.jpg"                 alt="1">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20241128161121752603/what-is-javascript.webp"                 alt="2">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20240829155421/Amazing-new-Javascript-features-in-ES15.webp"                 alt="3">         </div>         <button class="btn prev">‹</button>         <button class="btn next">›</button>     </div> </body> </html> 

In this example

  • Body: Center content both vertically and horizontally, with a light background and no margin/padding.
  • Carousel: Restrict width to 80% with a max of 600px, and hide any overflow.
  • Image Wrapper: Arrange images in a row using flex, with smooth transition on transformation.
  • Images: Set images to take full width, keeping their aspect ratio intact.
  • Buttons: Position buttons (prev/next) in the center vertically, with semi-transparent background.
  • Button Hover: Darken button background on hover for better visibility.
  • Prev Button: Position the previous button to the left.
  • Next Button: Position the next button to the right.

Carousel - JavaScript Functionality

we add the functionality for navigating between images, as well as autoplay that switches the images automatically.

JavaScript
const prev = document.querySelector('.prev'); const next = document.querySelector('.next'); const wrap = document.querySelector('.img-wrap'); const imgs = document.querySelectorAll('.img-wrap img');  let idx = 0;  function showImg() {     if (idx >= imgs.length) idx = 0;     if (idx < 0) idx = imgs.length - 1;     wrap.style.transform = `translateX(-${idx * 100}%)`; }  next.addEventListener('click', () => {     idx++;     showImg(); });  prev.addEventListener('click', () => {     idx--;     showImg(); });  setInterval(() => {     idx++;     showImg(); }, 3000);  showImg(); 

In this example

  • prev and next buttons for navigation are selected using querySelector.
  • wrap refers to the container for the images.
  • imgs holds all the individual images inside the wrap.
  • idx is a variable to keep track of the currently displayed image.
  • If idx is greater than or equal to the number of images, reset it to 0.
  • If idx is less than 0, reset it to the last image index.
  • Moves the wrap by updating its transform style to shift images horizontally based on the current idx.
  • Next Button: Increments idx and calls showImg() to display the next image.
  • Previous Button: Decrements idx and calls showImg() to display the previous image.
  • Uses setInterval to increment idx every 3000ms (3 seconds) and updates the displayed image via showImg().

Complete Code

HTML
<html> <head>     <title>Vanilla JavaScript Carousel</title>     <style>         body {             font-family: Arial, sans-serif;             margin: 0;             padding: 0;             display: flex;             justify-content: center;             align-items: center;             height: 100vh;             background: #f4f4f4;         }         .car {             position: relative;             width: 80%;             max-width: 600px;             overflow: hidden;             border-radius: 10px;             box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);         }         .img-wrap {             display: flex;             transition: transform 0.5s ease;         }          .img-wrap img {             width: 100%;             height: auto;             flex-shrink: 0;         }         .btn {             position: absolute;             top: 50%;             transform: translateY(-50%);             background: rgba(0, 0, 0, 0.5);             color: #fff;             border: none;             padding: 10px;             font-size: 16px;             cursor: pointer;             border-radius: 50%;         }          .btn:hover {             background: rgba(0, 0, 0, 0.8);         }          .prev {             left: 10px;         }          .next {             right: 10px;         }     </style> </head> <body>     <div class="car">         <div class="img-wrap">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20241228102812942963/0_ilw552fVUGbwIzbE.jpg" alt="Image 1">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20241128161121752603/what-is-javascript.webp" alt="Image 2">             <img src="https://media.geeksforgeeks.org/wp-content/uploads/20240829155421/Amazing-new-Javascript-features-in-ES15.webp" alt="Image 3">         </div>         <button class="btn prev">‹</button>         <button class="btn next">›</button>     </div>     <script>         const prev = document.querySelector('.prev');         const next = document.querySelector('.next');         const wrap = document.querySelector('.img-wrap');         const imgs = document.querySelectorAll('.img-wrap img');         let idx = 0;         function showImg() {             if (idx >= imgs.length) idx = 0;             if (idx < 0) idx = imgs.length - 1;             wrap.style.transform = `translateX(-${idx * 100}%)`;         }         next.addEventListener('click', () => {             idx++;             showImg();         });          prev.addEventListener('click', () => {             idx--;             showImg();         });         setInterval(() => {             idx++;             showImg();         }, 3000);         showImg();     </script> </body> </html> 

Next Article
Building a Carousel with Vanilla JavaScript

T

tanmxcwi
Improve
Article Tags :
  • HTML
  • javascript-basics
  • JavaScript-Projects

Similar Reads

    What is Vanilla JavaScript ?
    Vanilla JavaScript refers to using pure JavaScript without relying on any additional libraries or frameworks. It’s the basic, straightforward form of JavaScript, often referred to as "plain" JavaScript. Simple and lightweightDirect interaction with DOMFlexibility and CustomizableWhy “Vanilla”?The te
    4 min read
    Create an Autoplay Carousel using HTML CSS and JavaScript
    An Autoplay Carousel is a dynamic UI element that automatically cycles through a series of images or content slides, providing a visually engaging way to display information. It enhances user experience by showcasing multiple items in a limited space without manual navigation. This can be implemente
    2 min read
    Automatic Image Slider using JavaScript
    In this article, we will discuss how to create an automatic image slider using JavaScript. An image slider is a popular component of modern websites that allows the display of multiple images in a single location, usually in a sliding motion. With the use of JavaScript, creating an automatic image s
    3 min read
    Animated Slideshow App in HTML CSS & JavaScript
    We will learn to create a slideshow of multiple images. This slideshow will transition between the images every few seconds. we will further learn to align the images, style the images, and make the animation look better.PrerequisitesHTMLCSSJSApproachCreate 3 files one for HTML, one for CSS, and one
    3 min read
    Create A Draggable Card Slider in HTML CSS & JavaScript
    In this article, we will demonstrate how to create a draggable card slider using HTML, CSS, and JavaScript. We'll use a GeeksforGeeks card slider as an example and implement the functionality to slide cards left and right using arrow buttons. Additionally, we'll incorporate the draggable option, all
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences