Creating an Image Slider using JS and CSS Tutorial

In this tutorial, you will learn how to create an Image Slider using JavaScript and CSS. The tutorial aims to provide the IT/CS students and new programmers with a reference for learning to implement a creative feature of web application using JavaScript and Cascading Stylesheet (CSS). Here, snippets of a sample program that demonstrate how to achieve the tutorial's objectives are provided. The snippets' complete source code zip file is also provided and is free to download.

What is an Image Slider?

Image Slider is an animated feature in a certain program that displays images using a sliding animation. This feature is used for implementing a slideshow panel or feature for a certain website or web application.

How to Create an Image Slider using JavaScript and CSS?

Image slider can be achieved in many ways. There are also lots of plugins or libraries available that you can use to implement the said feature in your websites such as the Bootstrap Carousel. Using JS and CSS combined, we can create an Image Slider from scratch. Using CSS, we can design the said feature interface and for its functionalities, we can use the event listeners and the built-in methods of JavaScript for implementing the functionalities of the Image Slider.

Simple Image Slider App Source Code

Here are the snippets of the simple demo Image Slider App that I created for this tutorial that demonstrates how to achieve the features and functionalities of an Image Slider using JS and CSS. The source code only used the Bootstrap Framework for the design of some elements.

CSS

The snippet below is a CSS file containing the stylesheet's script for the design and animation of the Image Slider. The file is known as style.css.

  1. html, body{
  2.     height: 100%;
  3.     width: 100%;
  4. }
  5. body{
  6.     display: flex;
  7.     height: 100%;
  8.     width: 100%;
  9.     flex-direction: column;
  10. }
  11. body>nav, body>footer{
  12.     flex-shrink: 1;
  13. }
  14. body>main{
  15.     flex-shrink: 1;
  16.     flex-grow: 1;
  17.     overflow: auto;
  18.     margin: 1em 0;
  19.     display: flex;
  20.     align-items: center;
  21. }
  22. .slider-container {
  23.     position: relative;
  24.     overflow: hidden;
  25. }
  26. .slider-images {
  27.     position: relative;
  28.     width: 100%;
  29.     overflow: hidden;
  30. }
  31. .slider-image-holder {
  32.     width: 100%;
  33.     position: relative;
  34.     height: 40vh;
  35.     float: left;
  36.     -webkit-backface-visibility: hidden;
  37.     backface-visibility: hidden;
  38.     transition: transform .9s ease-in-out;
  39.     margin-right: -100%;
  40.     display: none;
  41. }
  42. .slider-image-holder.active,
  43. .slider-image-holder.item-prev,
  44. .slider-image-holder.item-next {
  45.     display: block;
  46. }
  47. @media (prefers-reduced-motion:reduce) {
  48.     .slider-image-holder {
  49.         transition: none
  50.     }
  51. }
  52. .slider-image-holder.item-prev.active{
  53.     transform: translateX(-100%);
  54. }
  55. .slider-image-holder.item-next.active{
  56.     /* transform: translateX(-100%); */
  57. }
  58. .slider-image-holder.item-next.before-next{
  59.     transform: translateX(100%);
  60. }
  61. .slider-image-holder.item-next.before-next.reverse{
  62.     transform: translateX(-100%);
  63. }
  64. .slider-image-holder.item-prev.active.reverse{
  65.     transform: translateX(100%);
  66. }
  67. .slider-image-holder.no-transition{
  68.     transition: none
  69. }
  70. .slider-image-holder>img {
  71.     width: 100%;
  72.     height: 100%;
  73.     object-fit: cover;
  74.     object-position: center center;
  75. }
  76. .slider-controls {
  77.     position: absolute;
  78.     width: 100%;
  79.     height: 100%;
  80.     top: 0;
  81.     left: 0;
  82.     display: flex;
  83.     justify-content: space-between;
  84.     align-items: center;
  85. }
  86.  
  87. .slider-control-prev, .slider-control-next {
  88.     background: #ffffff61;
  89.     display: flex;
  90.     align-items: center;
  91.     justify-content: center;
  92.     width: 3.5vw;
  93.     height: 5vw;
  94.     font-size: 3em;
  95.     color: #000;
  96.     cursor: pointer;
  97. }

JavaScript

Here's the JavaScript file named slider.js. The file contains the script of the functionalities of the Image Slider.

  1. //current active slide index
  2. if(document.querySelector('.slider-image-holder.active') === null){
  3.     document.querySelector('.slider-image-holder:nth-child(1)').classList.add("active")
  4. }else{
  5.     //Get the active slide item's index
  6.     current_slide_idx = Array.from(document.querySelectorAll('.slider-image-holder')).indexOf(document.querySelector('.slider-image-holder.active'))
  7. }
  8. var curent_slide_el, next_slide_el;
  9. window.slider = function($prev = false){
  10.     var slider_count = document.querySelectorAll('.slider-image-holder').length
  11.     var current_slide_idx = Array.from(document.querySelectorAll('.slider-image-holder')).indexOf(document.querySelector('.slider-image-holder.active'))
  12.     current_slide_idx += 1;
  13.     if($prev === false){
  14.         if(slider_count == current_slide_idx){
  15.             var next_slide_idx = 1;
  16.         }else{
  17.             var next_slide_idx = current_slide_idx +1;
  18.         }
  19.     }else{
  20.         if(current_slide_idx == 1){
  21.             var next_slide_idx = slider_count;
  22.         }else{
  23.             var next_slide_idx = current_slide_idx - 1;
  24.         }
  25.     }
  26.    
  27.     curent_slide_el =  document.querySelector(`.slider-image-holder:nth-child(${current_slide_idx})`)
  28.     next_slide_el =  document.querySelector(`.slider-image-holder:nth-child(${next_slide_idx})`)
  29.         if($prev === true){
  30.             next_slide_el.classList.add('reverse')
  31.             curent_slide_el.classList.add('reverse')
  32.         }
  33.         next_slide_el.classList.add('no-transition')
  34.         next_slide_el.classList.add('before-next')
  35.         next_slide_el.classList.remove('no-transition')
  36.         next_slide_el.classList.add('item-next')
  37.         setTimeout(()=>{
  38.             next_slide_el.classList.remove('before-next')
  39.             curent_slide_el.classList.add('item-prev')
  40.             // curent_slide_el.classList.remove('item-prev')
  41.             // next_slide_el.classList.remove('item-next')
  42.            
  43.             // curent_slide_el.classList.remove('active')
  44.             // next_slide_el.classList.add('active')
  45.             curent_slide_el.addEventListener('transitionend', function(e){
  46.                 e.preventDefault();
  47.                 curent_slide_el.classList.remove('item-prev')
  48.                 curent_slide_el.classList.remove('reverse')
  49.                 curent_slide_el.classList.remove('active')
  50.                 next_slide_el.classList.add('active')
  51.                 next_slide_el.classList.remove('item-next')
  52.                 if($prev === true){
  53.                     next_slide_el.classList.remove('reverse')
  54.                     curent_slide_el.classList.remove('reverse')
  55.                 }
  56.                 document.querySelectorAll('.slider-control-prev, .slider-control-next').forEach(el => {
  57.                     this.style.pointerEvents = 'auto';
  58.                 });
  59.             })
  60.         }, 100)
  61.        
  62.             return false;
  63. }
  64. document.querySelector('.slider-control-prev').addEventListener('click', function(e){
  65.     e.preventDefault()
  66.     loop_slide_end()
  67.     document.querySelectorAll('.slider-control-prev, .slider-control-next').forEach(el => {
  68.         this.style.pointerEvents = 'auto';
  69.     });
  70.     slider(true)
  71. })
  72. document.querySelector('.slider-control-next').addEventListener('click', function(e){
  73.     e.preventDefault()
  74.     loop_slide_end()
  75.     document.querySelectorAll('.slider-control-prev, .slider-control-next').forEach(el => {
  76.         this.style.pointerEvents = 'auto';
  77.     });
  78.     slider()
  79. })
  80.  
  81. var loop_slide;
  82. window.loop_slide_start = function(){
  83.     loop_slide =setInterval(()=>{ slider() }, 3000)
  84. }
  85. window.loop_slide_end = function(){
  86.     clearInterval(loop_slide)
  87. }
  88. window.onload = function(){
  89.     loop_slide_start()
  90. }

Interface

The below snippet is an HTML file named index.html. It contains the interface elements scripts that display the Image Slider. The slider.js and style.css are loaded on the script. Please replace the image source path with the images that you downloaded or that you desire to use on your end.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Image Slider - JS and CSS</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <link rel="stylesheet" href="style.css">
  10.     <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
  11.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13.  
  14. </head>
  15. <body style="background:#EEF1FF">
  16.     <nav class="navbar navbar-expand-lg navbar-dark" style="background:#7FBCD2">
  17.         <div class="container">
  18.             <a class="navbar-brand" href="./">Image Slider - JS and CSS</a>
  19.             <div>
  20.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  21.             </div>
  22.         </div>
  23.     </nav>
  24.  
  25.     <main class="container-fluid">
  26.         <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
  27.             <div class="card mt-3 rounded-0">
  28.                 <div class="card-body rounded-0">
  29.                     <div class="container-fluid">
  30.                         <div class="slider-container">
  31.                             <div class="slider-images">
  32.                                 <div class="slider-image-holder">
  33.                                     <img src="./images/image1.jpg" alt="">
  34.                                 </div>
  35.                                 <div class="slider-image-holder">
  36.                                     <img src="./images/image2.jpg" alt="">
  37.                                 </div>
  38.                                 <div class="slider-image-holder">
  39.                                     <img src="./images/image3.jpg" alt="">
  40.                                 </div>
  41.                             </div>
  42.                             <div class="slider-controls">
  43.                                 <div class="slider-control-prev"><i class="fa-solid fa-angle-left"></i></div>
  44.                                 <div class="slider-control-next"><i class="fa-solid fa-angle-right"></i></div>
  45.                             </div>
  46.                         </div>
  47.                     </div>
  48.                 </div>
  49.             </div>
  50.         </div>
  51.     </main>
  52. <footer class="container-fluid py-3" style="background:#7FBCD2; color:#fff">
  53.     <div class="container-fluid my-2">
  54.         <div class="text-center">
  55.             <b>Image Slider - JS/CSS &copy; 2022</b>
  56.         </div>
  57.     </div>
  58. </footer>
  59. <script src="slider.js"></script>
  60. </body>
  61. </html>

Application Snapshot

How does the Image Slider App work?

This Demo Image Slider App displays the images infinitely with 3 seconds intervals before showing the next image. The slide also has previous and next controls to navigate the images manually. When the controls have been triggered, the slideshow will stop automatically.

There you go! You can now test the source code on your end and see if it works properly and achieve the goal of this tutorial. The complete source code zip file that I created can be downloaded by clicking the download button located after this article's content.

That's the end of this tutorial. I hope this Image Slider using JavaScript and CSS Tutorial helps you to improve your programming capabilities and you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment