Course Content
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
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
index
index
index
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.
index
index
index
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.
index
index
index
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>
elementsideItem
: reference to each slide element;prevBtn
andnextBtn
: 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.
Thanks for your feedback!