Google trends Public Holidays Coupon Code Code Compiler

Creating An Image Slider Using JavaScript HTML And CSS Only


Dec 25, 2018

Creating An Image Slider Using JavaScript HTML And CSS Only

We are going to learn how to create a simple images slider using HTML, CSS, and JavaScript only. Here, we are not using any external frameworks/plugins for slider.

If the slider requirement is simple and short, building your own slider using HTML and JavaScript can be one of the best ways to achieve it. This will take less time to implement and give no conflicts/errors.

CSS Code:

First apply CSS to showcase the images in a proper position with some styles. Below is the code


 .container{
    max-width: 980px;
    margin: auto;
    position: relative;
 }
 .icon{
   width: 25px;
   line-height: 40px;
   background: black;
   color: white;
   text-align: center
 }
 .left{
   position: absolute;
   top: 50%;
   left: 0%;
   transform: translate(0%,-50%);
 }
 .right{
   position: absolute;
   top: 50%;
   right:  0%;
   transform: translate(0%,-50%);
 }

HTML Code:

Add the below code in body section of the HTML page.


<div class="container">
  <img class="myslider" src="images/01.jpg" >
  <img class="myslider" src="images/02.jpg" >
  <img class="myslider" src="images/03.jpg" >
   <a class="icon left" >&#10094;</a>
  <a class="icon right" >&#10095;</a>

</div>


Write the JavaScript code. Considering it a small example, I am writing the code in the same HTML page using [removed][removed].

JavaScript Code:


            var index =1;
            showdiv(index);
            function getdiv(n){
                showdiv(index +=n);
            }
            
            function showdiv(n){
                var i;
                var a = document.getElementsByClassName("myslider");
                if(n > a.length){
                    index = 1;
                }
                if(n<1){
                    index = a.length;
                }
                for(i=0; i<a.length; i++){
                    a[i].style.display = "none";
                }
                a[index-1].style.display = "block";
            }

Copyright 2024. All rights are reserved