Dynamic custom carousel – HTML & Javascript
In this article, we are going to teach you how you can create a dynamic custom carousel. If you are a web developer, you might have already came across with bootstrap carousel, which is basically a slider. Although, it shows you the functionality to show slides, move next/previous and many more. But nothing gives you more control than writing the code by yourself. Sometimes, you just want to learn the algorithms that how these sliders are created. So we will create a dynamic custom carousel using HTML, Javascript & PHP. If you do not want to fetch the slider images from database, you can skip the PHP part and jumps to the Javascript part.
What we are going to do ?
We will be fetching data from database and display in slides, thus makes our custom carousel dynamic. The database we will be using is named “tutorials” and the table whom we will be fetching data is “posts”. It has 3 fields (id, title, image). We will not be using ID attribute, it is just for unique identification and relationship between different tables. We will be displaying title and image in each slide.
First, create a database named “tutorials”. Create a table named “posts” and insert data in it using the following query:
CREATE TABLE `posts` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` text NOT NULL,
`image` text NOT NULL
);
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`id`, `title`, `image`) VALUES
(1, 'image 1', 'https://i.pinimg.com/originals/f8/d9/a7/f8d9a791ed9cd56f4970513d8797459d.png'),
(2, 'image 2', 'https://i.pinimg.com/564x/32/93/81/32938198ee16b5b2339a9071c8eb454f.jpg'),
(3, 'image 3', 'https://i.pinimg.com/564x/f3/ac/41/f3ac41a686ceff77bf9473827df5476c.jpg');
Slides
Then you need to connect with its database using PHP and fetch all the images for slider. Again, you can create a simple PHP array and enter the URL of all the images and their titles which you wanted to be displayed in each slide. But in most of the cases, there are images which are added from admin panel. In this case, you need to simply fetch all images from that table and display them in slides.
<?php
$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");
$result = mysqli_query($conn, "SELECT * FROM posts");
$count = 0;
$posts = array();
while ($row = mysqli_fetch_object($result)):
array_push($posts, $row);
?>
<div class="post <?php echo $count == 0 ? 'active' : ''; ?>">
<p><?php echo $row->title; ?></p>
<img src="<?php echo $row->image; ?>" style="width: 500px;">
</div>
<?php
$count++;
endwhile;
?>
You have seen that we created a <div> tag and it has 2 classes, post & active. But active class will be given only to the first div element. This is because we want to show the first slides first. To display other slides we will create 2 buttons next & previous. We have also created a PHP array $posts which will have all the slides. Use this variable to move next and previous slides. We will also teach you how you can convert a PHP variable, object or an array into a Javascript variable. For each slide, we are displaying its title and an image. Now we will apply some CSS to hide the slides which does not have a class “active”. And display the only slide which has an “active” class.
<style>
.post {
display: none;
}
.post.active {
display: block;
}
</style>
Slide indicators
Now we will create a <div> which will hold the next and previous slides indicators. If you have ever used bootstrap carousel then you might already be familiar with it. If you are not, indicators are the buttons which are used to show the next or previous slide. The basic algorithm is, if the next indicator is clicked, then you get next slide <div> element, hide the currently active <div> and show the next slide. Same goes for previous indicator, only different is, you have to get the previous <div> element instead of the next. We will also be displaying next slide’s name so the user can know which slide will be displayed next. It will be treated just as a reference.
<div class="links">
<div class="previous-post" onclick="showPrevious();">
<div style="display: contents; cursor: pointer;">
<p>
<b>previous post</b>
</p>
<p id="previous-post-title"></p>
</div>
</div>
<div class="next-post" onclick="showNext();" style="margin-left: 100px;">
<div style="display: contents; cursor: pointer;">
<p>
<b>next post</b>
</p>
<p id="next-post-title"></p>
</div>
</div>
</div>
Using PHP variable in Javascript
Now we will come to the part where we promised that we will teach you how you can convert a PHP variable into a Javascript variable. If you have followed the tutorial so far, you might already have a $posts PHP array. Now you want to use this in your Javascript code. Simply we will create a hidden input field, give it an ID so we can get it in Javascript. And set the value to that PHP array. But since $posts is an array, so we have to convert that into JSON format. We can do that simply by calling a PHP built-in function json_encode. Now when the array is converted into JSON, some characters might create trouble for you while setting it as a value of input field. So you have to wrap your function inside another PHP built-in function htmlentities.
<input type="hidden" id="posts" value="<?php echo htmlentities(json_encode($posts)); ?>">
Next and previous slide
Now when the page loads, we will get this input field value using its ID. Since we converted that into JSON, now we have to parse it in Javascript objects or array. We can do that by simply calling a function JSON.parse. It will convert the PHP variable into a proper Javascript variable. Now you can use this array anywhere in your Javascript code. The following code will show the next indicator only if there is a slide afterwards. Similarly it will show the previous indicator only if there is a slide before.
<script>
var currentIndex = 0;
window.addEventListener("load", function () {
postsArray = document.getElementById("posts").value;
postsArray = JSON.parse(postsArray);
renderTitle();
});
function showPrevious() {
currentIndex--;
var previous = document.querySelector(".post.active").previousElementSibling;
document.querySelector(".post.active").className = "post";
previous.className = "post active";
renderTitle();
}
function showNext() {
currentIndex++;
var next = document.querySelector(".post.active").nextElementSibling;
document.querySelector(".post.active").className = "post";
next.className = "post active";
renderTitle();
}
function renderTitle() {
document.querySelector(".previous-post").style.visibility = "hidden";
document.querySelector(".next-post").style.visibility = "hidden";
if (postsArray[currentIndex + 1] != null) {
document.querySelector(".next-post").style.visibility = "visible";
document.getElementById("next-post-title").innerHTML = postsArray[currentIndex + 1].title;
}
if (postsArray[currentIndex - 1] != null) {
document.querySelector(".previous-post").style.visibility = "visible";
document.getElementById("previous-post-title").innerHTML = postsArray[currentIndex - 1].title;
}
}
</script>
Explanation
You can also see the renderTitle() function, we will come back to that later. First we created a variable named currentIndex and initialize it with 0. That is the index of current slide visible to the user.
When the next or previous indicator is clicked, we are calling a function which will increment the value of currentIndex if next indicator is clicked. And decrement the value if previous indicator is clicked.
Then we are getting the next slide’s <div> using nextElementSibling and removing the “active” class from currently active slide. Finally we are setting the “active” class to next slide. That’s how current slide will be hidden and next slide will be displayed.
renderTitle()
Now come to the renderTitle() function. It is called 3 times, one when the page loads, one when next slide indicator is clicked. And one when previous slide indicator is clicked. This function has 3 purposes: first to hide both next and previous slide indicators. Second is to show the next indicator only if there is a slide next. Similarly show the previous indicator only if there is a slide before.
We already have a postsArray array which holds all the slide elements so we can check easily. Third purpose of this function is to show the title of next and previous slide. So, the user can know on which slide he is going to see next.
Hope this tutorial helps you create your own dynamic custom carousel which you can customize and design as per your need. You can add more features to it if you want. Try adding CSS animations, like making the slide move left or right when next and previous is clicked.
Also try to change the slide automatically after 5 seconds. The list of features can go on because it is a dynamic custom carousel and anyone can add more features in it as per needs. If you a minimalism lover, then you can also remove elements from it which you do not like. For example, you can remove the next and previous slide title to make space and make it more minimal.