Finally, after going through the core concepts in JavaScript, as well as how the language works in the browser environment, you are ready to create your first real project using HTML, CSS, and JavaScript.
In this lesson, we are going to walk through how to build an image slider. We will demonstrate two different approaches, one opacity
based and the other transform
based.
Creating HTML
Let's first start with the HTML code:
1<div class="slider">
2 <div class="slide">
3 <img src="/media/course/javascript/1.jpg" alt="demo image" />
4 </div>
5 <div class="slide">
6 <img src="/media/course/javascript/2.jpg" alt="demo image" />
7 </div>
8 . . .
9 <a class="prev" onclick="prevSlide()"><</a>
10 <a class="next" onclick="nextSlide()">></a>
11</div>
.slider
acts as the container for the entire image slider.- Individual slide is enclosed in a
.slide
container along with the image. - The slider navigation is controlled by two links,
.prev
and.next
.
We also have the onclick
event listener set up for the navigation links, and when they are clicked, the corresponding JavaScript functions will be activated.
Of course, you could use the addEventListener()
function. But because this example doesn't require callbacks that are too complex, we'll use the HTML attribute method here.
Adding styles
For easier styling of elements, it is recommended to remove the default paddings and margins of all elements, and set box-sizing
to border-box
. This allows the elements to be sized based on their border-box
dimensions rather than content-box
.