Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating a Carousel with HTML + JavaScript | Beginner Projects with HTML + JavaScript
HTML & JavaScript Interactivity for Beginners
course content

Conteúdo do Curso

HTML & JavaScript Interactivity for Beginners

HTML & JavaScript Interactivity for Beginners

1. DOM and HTML Manipulation
2. DOM Event Handling and Forms
3. JavaScript HTML5 APIs
4. Beginner Projects with HTML + JavaScript

Creating a Carousel with HTML + JavaScript

In this chapter, we'll create a carousel in plain Javascript. This is a basic slider where we've created the Slider containers and slid them with JavaScript, and then you can add any images, text content, or even videos.

Let's get started in creating the basic structure of its HTML.

Step1: Creating the Markup for the Slider

html

index

css

index

js

index

copy

Let's add some styles to it to make it move like a carousel.

Step2: Styling the Carousel

You need to add the following styles in a <style> tag in the <head> tag.

html

index

css

index

js

index

copy

Although CSS is beyond the scope of this chapter, a couple of things to note here:

  • The <ul> element is given a fixed height of 250px as we want to move backward and forward a group of li elements with a background color. The <ul> element's overflow property is hidden so that other slides are hidden;
  • The button controls previous and next are the ones that move the slides back and forth.

Step3: Adding Functionality to the Slider

Now it's the fun part with JavaScript. Add the below code to the script tag after the close of the style tag.

html

index

css

index

js

index

copy

Program Explanation
Since we've put the <script> tag in the <header> tag, we need to wait till the window loads. You can achieve it with the window.onload() event handler where it is assigned to a function. Then there are four constants and each of which are:

  • containerSlides: the reference to the <ul> element
  • sideItem: reference to each slide element;
  • prevBtn and nextBtn: references to previous slide next and previous buttons.

Then we attach event listeners to the previous and next buttons. After that, attach event listeners to the previous and next buttons. Then in the case of the next button, the scrollLeft property of the <ul> element is increased by the clientwidth, the width of the slide with padding, but not margin, borders or scrollbar.

This is it for the time being, and you can experiment with pagination and adding content for sliders for advanced features.

What does the clientWidth of an HTML element return?

Selecione a resposta correta

Tudo estava claro?

Seção 4. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt