Step 1
Create a folder named “images” in the project path and put all the images required for the slider. Make sure that all the images are in the same size (width*height). Otherwise, the slider will misbehave while navigating between slides.
Step 2
Add the below code in body section of the HTML page.
- <body>
- <div class=“slidercontainer”>
- <div class=“showSlide fade”>
- <img src=“images/img1.jpg” />
- <div class=“content”>Lorem ipsum dolor sit amet</div>
- </div>
- <div class=“showSlide fade”>
- <img src=“images/img2.jpg”/>
- <div class=“content”>Lorem ipsum dolor sit amet</div>
- </div>
-
- <div class=“showSlide fade”>
- <img src=“images/img3.jpg”/>
- <div class=“content”>Lorem ipsum dolor sit amet</div>
- </div>
- <div class=“showSlide fade”>
- <img src=“images/img4.jpg”/>
- <div class=“content”>Lorem ipsum dolor sit amet</div>
- </div>
- <!– Navigation arrows –>
- <a class=“left” onclick=“nextSlide(-1)”>❮</a>
- <a class=“right” onclick=“nextSlide(1)”>❯</a>
- </div>
- </body>
Here, <div class=”slidercontainer”> is the main container for slider and <div class=”showSlide fade”> are the slider images section that are repeating.
Step 3
Write the JavaScript code. Considering it a small example, I am writing the code in the same HTML page using <script type=”text/javascript”></script>.
If required, you can create an external JS file in the project path and refer it to the HTML page.
- <script type=“text/javascript”>
- var slide_index = 1;
- displaySlides(slide_index);
- function nextSlide(n) {
- displaySlides(slide_index += n);
- }
- function currentSlide(n) {
- displaySlides(slide_index = n);
- }
- function displaySlides(n) {
- var i;
- var slides = document.getElementsByClassName(“showSlide”);
- if (n > slides.length) { slide_index = 1 }
- if (n < 1) { slide_index = slides.length }
- for (i = 0; i < slides.length; i++) {
- slides[i].style.display = “none”;
- }
- slides[slide_index – 1].style.display = “block”;
- }
- </script>
All the above functions are user defined. We just only write some logic to read the slides and showing.
Step 4
Now, it’s time to apply CSS to showcase the images in a proper position with some styles. Below is the final code —
HTML+JavaScript+CSS,