In this article, we'll build our image slider using JavaScript. By building this image slider project, you will revise your JavaScript basics and learn concepts like arrays, the document object, events, etc., along with adding to the fun of building things on your own!
Setup
To get started, get a few images, an HTML file, a CSS file, and a JavaScript file:
First of all. we need to create the image slider's skeleton using HTML and style it with some CSS. At this point, our image slider won't work.
Create one yourself or feel free to copy the below HTML and CSS if you want to focus only on learning the JavaScript part of the image slider project.
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Image Slider Demo</title>
</head>
<body>
<div id="container">
<div class="btn" id="prev"><</div>
<img src="images/japan.jpg" id="pic">
<div class="btn" id="next">></div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
padding: 20px;
}
#container {
display: flex;
align-items: center;
justify-content: center;
width: fit-content; margin: 20px auto;
padding: 20px;
border-radius: 20px;
box-shadow: 0 0 20px #00000044;
}
.btn {
margin: 20px;
background-color: blanchedalmond;
padding: 14px 20px 20px 20px;
border-radius: 40px;
font-family: cursive;
font-size: 30px;
transition: background-color 0.08s ease-in;
border: 1px solid #00000044;
}
.btn:hover {
background-color: rgb(219, 196, 159);
cursor: pointer;
transition: background-color 0.08s ease-in;
}
img {
width: 640px;
height: 400px;
object-fit: fill;
}
Here's how it should look like:
Now that you have the slider all set up, it is time to make it functional!
The JavaScript part
Make sure that your JavaScript file is linked to your HTML document after all other elements in the <body>
tag:
<script src="script.js"></script>
Open the script.js file to start writing some code!
Getting the buttons to work:
In order to make the HTML elements (in our case, the buttons the image) to do any work, we need to be able to refer to them through JavaScript code.
JavaScript has a built-in object called document
that provides a method called getElementById()
that will help us refer to the buttons and the image (and any element in our HTML). The best way to use them is to create variables and store their reference. Make sure the IDs matches the ones you used in your HTML. Here is the code that works for the above HTML
var picture = document.getElementById("pic");
var prevBtn = document.getElementById("prev");
var nextBtn = document.getElementById("next");
Setup the images and the counter:
In order to be able to use our images, let us save them in an array.
var images = [
"images/varanasi.jpg",
"images/sanfrancisco.jpg",
"images/japan.jpg",
"images/dubai.jpg"
];
I have four images inside the images folder (as shown above). And thus, 4 array elements.
For the image slider to work properly, we will have to keep track of the index of the current image we have in the slider, which is the first element in the array, i.e., 0
. In JavaScript, the first element's index starts with 0
and the last element is arrayName.length - 1
. So, let us initialize a variable called num
to keep track of the image in the image slider.
var num = 0;
Handling Events
Let's start by understanding events.
JavaScript allows you to define what should happen when the user does something. User interactions on web pages are called Events. You can access these events through JavaScript code. Here are some example events:
Event | Description |
click | when an element is clicked |
mouseover | when the mouse pointer is over an element |
mouseleave | when the mouse leaves an element |
To handle one of these events on an HTML element, we need to add an event listener. To do this, we use the .addEventListener()
on the element reference variables we created using doument.getElementById()
Here is an example:
// Syntax:
elementRef.addEventListener("event_name", () => {
// Code goes here
});
// Example:
var myElem = document.getElementById("myElemeId");
myElem.addEventListener("click", () => {
alert("You clicked an HTML Element!");
});
The Algorithm
Now, let's talk about the logic of the image slider. Remember that we kept track of the current image's index in a variable called num
? Manipulating this number with the help of the two buttons we created will change the image in the view.
When the next/right button (referred to as nextBtn
) is clicked, the value of num
is increased by 1
, which changes the image in the slider to show the next image in the images array. And when num
exceeds 3
, that is, the last image's index, we set num = 0
. Similarly, num
is decreased by 1
every time the previous/left button is clicked, and reset to num = array_name.lenght - 1
, that is, the last index value, when it crosses 0.
// Algorithm
On Clicking the next button:
1. num = num + 1
2. if num == length_of_array:
num = 0
3. change the source url of the image tag with num as index
// Similarly,
On Clicking the next button:
1. num = num - 1
2. if num == 0:
num = length_of_array - 1
3. change the source url of the image tag with num as index
Putting the pieces together
Finally, it is time to put all the pieces together. Try to combine the logic with the event listeners on the reference variables we created earlier!
Here is the code of the event listeners for the two buttons:
// Next Button Event Listener:
nextBtn.addEventListener("click", () => {
num++;
if(num==images.length){
num = 0;
}
picture.src = images[num];
});
// Previous Button Event Listener.
prevBtn.addEventListener("click", () => {
num--;
if(num<0){
num = images.length - 1;
}
picture.src = images[num];
});
Here,
pictures
is an HTML image element that is accessed using thedocument
object. So, we get to access the images source with the help of the.src
property.
Here is a final demo of the image slider:
And... we are done!
Great work! You have just practice the following things using JavaScript:
Arrays
Events
document
objectHow to manipulate HTML using JavaScript
Turning algorithm into code that makes the image slider work!
This is a great beginning for you to try out more advanced features, build more projects with them, and continue your JavaScript journey into the world of JS Web Frameworks. All the best!