Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to create a image slider animation. To create this animation we will use HTML,CSS, and Javascript. We do not make use of any images, icons or external libraries and plugins to create this animation.
As I have mentioned in my tutorials before, this kind of animation hardly finds application in real-world projects. However, they are a fun way to learn and explore new CSS properties and Javascript.
Image slider animation allow you to display multiple images in a smooth and dynamic way using HTML, CSS, and JavaScript. the slider smoothly transitions between images with a sliding animation. with navigation buttons (next/prev), user can easily browse through the image gallery. the slider is responsive and ideal for portfolio.
Project Folder Structure:
Before we start coding let us take a look at the project folder structure. We create a project folder called – ‘Image Slider’. Inside this folder, we have three files. These files are – index.html,style.css and script.js. The first file is the HTML document while the second one is the stylesheet. last one file is javascript.
HTML:
We begin with the HTML code. First, copy the code below and paste it into your HTML document.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Image Slider | Codehemu</title>
<link href="https://www.codehemu.com/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="slider">
<div class="widget">
<div class="image-slider">
<div class="slide"></div>
<div class="slider-directionnav">
<a class="slider-previous"><</a>
<a class="slider-next">></a>
</div>
<div class="slider-caption"></div>
</div>
<div class="image-thumbnail"><ul></ul></div>
</div>
</div>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
CSS:
Next, we style the elements created by HTML to give them shape and add animation using CSS. Now copy the code provided to you below and paste it into your stylesheet.
body {
margin: 0;
padding: 0;
background: #58DDAF;
}
.container {
position: relative;
float: left;
width: 100%;
margin: 0 auto;
}
.slider{
height: auto;
min-height: 320px;
max-height: 600px;
margin: 0 auto;
border: 0;
border-radius: 0;
box-shadow: none;
padding: 5px 0 0;
}
.slider{
width: 1078px;
}
.widget {
border: 0;
width: 100%;
margin: 0 auto;
text-align: center;
position: relative;
background-color: transparent;
}
.image-slider img {
top: 0;
margin: auto;
height: auto;
opacity: 1;
max-width: 100%;
max-height: 450px;
position: relative;
transition: opacity 1s ease-in-out;
border: 1px solid #e6e6e6;
}
.image-slider .hidden {
height: 0;
z-index: -1;
opacity: 0
}
.slider-directionnav a {
opacity: 0;
cursor: pointer;
transition: all .2s ease-in-out;
}
.slider-directionnav a {
opacity: 1;
}
.slider-next,
.slider-previous {
top: 25%;
font-family: monospace;
font-weight: bold;
font-size: 10vw;
position: absolute;
color: rgba(0,0,0,.1)!important;
}
.slider-next {
right: 10px;
float: right;
}
.slider-previous {
left: 10px;
float: left;
}
.slider-next:hover,
.slider-previous:hover {
color: rgba(0,0,0,.4)!important
}
.slider-caption{
overflow: hidden;
-webkit-line-clamp: 1;
padding: 0; width: 100%;
height: 32px;
font-size: 1em;
margin: 5px 0 0 0;
line-height: 32px;
}
.image-thumbnail .markborder {
border-bottom: solid 10px rgba(0,0,0,.15)
}
.image-thumbnail img {
width: 32px;
height: auto;
opacity: 1;
margin: 10px;
max-width: 100%;
cursor: pointer;
border-bottom: solid 1px transparent;
}
.image-thumbnail ul {
margin: 0;
padding: 0;
}
.image-thumbnail li { list-style: none }
.image-thumbnail li {display: inline}
@media screen and (max-width: 1165px) {
.slider {
width: 100%;
}
}
JavaScript:
Next, we style the elements created by HTML to give them shape and add animation using javascript. Now copy the code provided to you below and paste it into your script.js file.
function get_image_url(size, text, options = {}) {
const {
fontFamily = "Arial",
fontSize = 40,
textColor = "#000000",
backgroundColor = "#E0E0E0",
imageFormat = "image/png",
jpegQuality = 0.9
} = options;
const [width, height] = size;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// Set background color
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, width, height);
// Set text properties
ctx.font = `${fontSize}px ${fontFamily}`;
ctx.fillStyle = textColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Measure text to center it
const textMetrics = ctx.measureText(text);
const textWidth = textMetrics.width;
const textHeight = fontSize;
// Calculate position to center the text
const x = width / 2;
const y = height / 2;
ctx.fillText(text, x, y);
// Return the Data URL
if (imageFormat === "image/jpeg") {
return canvas.toDataURL(imageFormat, jpegQuality);
} else {
return canvas.toDataURL(imageFormat);
}
}
const sliderJson = [{
"title": "IMAGE SLIDE 1",
"link": "#",
"image": get_image_url([600,400], "IMAGE SLIDE 1"),
"icon": get_image_url([128,128], "1")
},{
"title": "IMAGE SLIDE 2",
"link": "#",
"image": get_image_url([600,400], "IMAGE SLIDE 2"),
"icon": get_image_url([128,128], "2")
},{
"title": "IMAGE SLIDE 3",
"link": "#",
"image": get_image_url([600,400], "IMAGE SLIDE 3"),
"icon": get_image_url([128,128], "3")
},{
"title": "IMAGE SLIDE 4",
"link": "#",
"image": get_image_url([600,400], "IMAGE SLIDE 4"),
"icon": get_image_url([128,128], "4")
}];
document.addEventListener('DOMContentLoaded', () => {
let currentIndex = 0;
const slider = document.querySelector(".image-slider .slide");
const thumbnail = document.querySelector(".image-thumbnail ul");
sliderJson.forEach((feed, i) => {
const {link, title, image, icon} = feed;
const a = document.createElement("a");
a.setAttribute("target", "_blank");
a.setAttribute("href", link);
const img = document.createElement("img");
img.className = "hidden";
img.setAttribute("title", title);
img.setAttribute("alt", title);
img.setAttribute("loading", "lazy");
img.src = image;
a.appendChild(img);
slider.appendChild(a);
const li = document.createElement("li");
const thumbnail_img = document.createElement("img");
thumbnail_img.setAttribute("title", title);
thumbnail_img.setAttribute("data-index", i);
thumbnail_img.setAttribute("loading", "lazy");
thumbnail_img.src = icon;
li.appendChild(thumbnail_img);
thumbnail.appendChild(li);
});
const images = document.querySelectorAll(".image-slider a img");
const thumbnails = document.querySelectorAll(".image-thumbnail img");
const caption = document.querySelector(".image-slider .slider-caption");
if (images.length === 0) return;
// Initialize the first slide and thumbnail
const initialTitle = images[currentIndex].getAttribute("title");
images[currentIndex].classList.remove("hidden");
thumbnails[currentIndex].classList.add("markborder");
if (initialTitle) {
caption.textContent = initialTitle;
}
function showSlide(index) {
currentIndex = index;
// Reset all images and thumbnails
images.forEach(img => img.classList.add("hidden"));
thumbnails.forEach(thumb => thumb.classList.remove("markborder"));
// Show the new slide and mark its thumbnail
images[currentIndex].classList.remove("hidden");
thumbnails[currentIndex].classList.add("markborder");
// Update the caption
const newTitle = images[currentIndex].getAttribute("title");
if (newTitle) {
caption.textContent = newTitle;
}
}
// Event listeners for navigation buttons
document.querySelector(".slider-next").addEventListener("click", function() {
const nextIndex = (currentIndex + 1) % images.length;
showSlide(nextIndex);
});
document.querySelector(".slider-previous").addEventListener("click", function() {
const prevIndex = (currentIndex - 1 + images.length) % images.length;
showSlide(prevIndex);
});
// Event listeners for thumbnails
thumbnails.forEach((thumbnail, index) => {
thumbnail.addEventListener("click", function() {
showSlide(index);
});
});
// Autoplay functionality
let intervalId;
function startAutoPlay() {
intervalId = setInterval(function() {
const nextIndex = (currentIndex + 1) % images.length;
showSlide(nextIndex);
}, 3000);
}
function stopAutoPlay() {
clearInterval(intervalId);
}
// Start autoplay on page load and control it on hover
startAutoPlay();
const homepageSlider = document.getElementById("homepage-slider");
if (homepageSlider) {
homepageSlider.addEventListener("mouseenter", stopAutoPlay);
homepageSlider.addEventListener("mouseleave", startAutoPlay);
}
});
That’s it for this tutorial. If you have any queries, suggestions or feedback you can comment below. Happy Coding!
إرسال تعليق