How to create simple slider with jQuery
There are plenty of great jQuery slider plugins/scripts out there, like bxSlider, but what if you need just simple slideshow and don’t want to use any of those scripts because they are overkill? No worries, it isn’t that hard to do, and we are going to go trough step by step to build one. We are going to create a basic slider with fade transition, not sliding transition, previous/next buttons and pager. So let’s start.
1. Markup
Markup for slider is very simple. We are going to create div with id slider as main container, and then div with class slides-container which is going to hold all the slides. We then just need another div that’s going to hold arrows and another that will act as pager.
<div id="slider"> <div class="slides-container"> <div class="slide"><img src="img/img-1.jpg" alt="Slider img 1" ></div> <div class="slide"><img src="img/img-2.jpg" alt="Slider img 2" ></div> <div class="slide"><img src="img/img-3.jpg" alt="Slider img 3" ></div> <div class="slide"> <div class="text"> Proof that you can use text and it works </div> </div> </div> <div class="arrows"> <a class="prev" href="#"><</i></a> <a class="next" href="#">></a> </div> <div class="pager"> 1 / 4 </div> </div>
Next we need to include the jQuery library and will for now just add $(document).ready() inside <script></script>. You can add this code just before closing </body> element.
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(function() { // Shorthand for $(document).ready() }); </script>
2. Styles
Before doing any jQuery we will add some styles to the slider that are needed for it to work properly.
We add width and height of the slider main container, height is very important here, if not set it will take height of each image in slide and it will be all very messed up. Another important thing here is postion: relative
because we need to set slides to position: absolute
. That way they are one beneath another and we will have smooth fade in-out transition.
#slider { width: 70%; height: 400px; margin: auto; position: relative; font-family: 'Roboto', Arial, Helvetica, sans-serif; font-size: 15px; } #slider .slides-container { position: relative; width: 100%; height: 100%; } #slider .slide { width: 100%; height: 100%; position: absolute; left: 0; top: 0; display: none; } #slider .slide:first-child { display: block; }
Next let’s just add some color to the text slide and font styling. We will set all images to 100% width and height of their container, and will add object-fit: cover
so that they display nicely (except in Edge, of course).
#slider .slide .text { width: 100%; height: 100%; background: #8fc6eb; color: #fff; text-transform: uppercase; font-size: 18px; font-weight: bold; text-align: center; } #slider img { width: 100%; height: 100%; object-fit: cover; }
Let’s style the pager just a bit, so it looks a bit nicer. Arrows need to be set to position: absolute;
so that we can position them with top property almost in the middle.
#slider .pager { font-size: 14px; font-weight: 900; color: #777; text-align: center; margin-top: 5px; } #slider .arrows a { position: absolute; text-decoration: none; color: rgba(255, 255, 255, 0.65); top: 43%; left: 15px; font-weight: 400; line-height: 1; font-size: 42px; } #slider .arrows a:hover { color: #fff; } #slider .arrows a.next { left: initial; right: 15px; }
If you wish for your slider to be bigger or smaller, only thing you will need to change is #slider width and height property.
3. jQuery magic
Here is where the fun begins 🙂 . First we have to set all the variables we will need later.
// Start autoplay var auto = true; // Pause duration between slides (ms) var pause = 7000; // Get parent element var $this = $('#slider'); // Slides container var slidesCont = $this.children('.slides-container'); // Get all slides var slides = slidesCont.children('.slide'); // Get pager div var pager = $this.children('.pager'); // Get Previous / Next links var arrowsCont = $this.children('.arrows'); var prevSlide = arrowsCont.children('.prev'); var nextSlide = arrowsCont.children('.next'); // Total slides count var slidesCount = slides.length; // Set currentSlide to first child var currentSlide = slides.first(); var currentSlideIndex = 1; // Holds setInterval for autoplay, so we can reset it when user navigates var autoPlay = null;
This bit of code needs to go inside the $(function() { });
$(function() { // Shorthand for $(document).ready() // code goes here });
After we got all the variables we need, let’s now continue first by hiding all of the slides except first one, adding a CSS class active to that slide and setting variable currentSlideIndex, which keeps the track on which slide we are, to one.
// Hide all slides except first and add active class to first slides.not(':first').css('display', 'none'); currentSlide.addClass('active');
Now we will create functions that actually do the job, fadeNext() and fadePrev(). Both of these work in very similar way, difference is just in checking if we are on the first or last slide. Function fadeNext() will firstly remove active class from current slide and then it will hide him. Next we need to check if we are on last slide. Let’s for the moment say we are not, instead we are on the first slide, then the function will increment currentSlideIndex by one, and currentSlide variable will move to the next slide (jQuery next()). Now that we have our next slide (2nd) selected we can fade it in and add class active to it, and that’s it, we transitioned to next slide.
Now, if we were on the last slide and “went” next, by default, function would go to the 5th slide, but that one does not exist. That’s why we have if statement here, that checks if we are on that last slide, and if we are, the function will jump to the first slide currentSlide = slides.first()
, then it will fade that slide into view and last set the currentSlideIndex to one.
fadePrev() works in almost the same way, just checks if we are on first slide and then selects the last slide in slides container, instead of slide 0, which of course does not exist.
// Function responsible for fading to next slide function fadeNext() { currentSlide.removeClass('active').fadeOut(700); if(currentSlideIndex == slidesCount) { currentSlide = slides.first(); currentSlide.delay(500).addClass('active').fadeIn(700); currentSlideIndex = 1; } else { currentSlideIndex++; currentSlide = currentSlide.next(); currentSlide.delay(500).addClass('active').fadeIn(700); } pager.text(currentSlideIndex+' / '+slidesCount); } // Function responsible for fading to previous slide function fadePrev() { currentSlide.removeClass('active').fadeOut(700); if(currentSlideIndex == 1) { currentSlide = slides.last(); currentSlide.delay(500).addClass('active').fadeIn(); currentSlideIndex = slidesCount; } else { currentSlideIndex--; currentSlide = currentSlide.prev(); currentSlide.delay(500).addClass('active').fadeIn(700); } pager.text(currentSlideIndex+' / '+slidesCount); }
Now we will create a function that will start the auto slideshow. Important thing in this function is that we reset timer/pause between slides. This is needed when person clicks next or previous arrow, so that the timer resets to firstly set value, otherwise it could happen that someone clicks next, and 2 seconds later slider transitions to another slide.
// Function that starts the autoplay and resets it // in case user navigated (clicked prev or next) function AutoPlay() { clearInterval(autoPlay); if(auto == true) autoPlay = setInterval(function() {fadeNext()}, pause); }
Last thing we need to do, is to transition the slides when user clicks on either next or prevous arrow, and call the AutoPlay function so the sliders autoplay starts is set true.
// Detect if user clicked on arrow for next slide and fade next slide if it did $(nextSlide).click(function(e) { e.preventDefault(); fadeNext(); AutoPlay(); }); // Detect if user clicked on arrow for previous slide and fade previous slide if it did $(prevSlide).click(function(e) { e.preventDefault(); fadePrev(); AutoPlay(); }); // Start autoplay if auto is set to true AutoPlay();
And that’s it! Now you have your own simple slider with fading transition.
PS It wouldn’t be a bad idea to actually wrap all of that code into function, so you can then create multiple sliders.
function dxSimpleSlider(element, auto = false, pause = 7000) { // slider code goes here }
You will need to remove var auto = true;
and var pause = 7000;
from our code, and change var $this = $('#slider');
to var $this = $(element);
when pasting into function.
Now you can use it very simply:
dxSimpleSlider('#slider', true, 6000); dxSimpleSlider('#slider-two', false, 4000); dxSimpleSlider('#slider-three', false, 10000);
Complete code can be found here Download
i am looking multiple slider in the same page. but it is not working.
Hey Ahmed, it should work if you follow step by step. You will need to create some wrapper function to use it on multiple sliders (last 2 pieces of code)
Hey Ivan, thank you for the simple slider.
Just a small suggestion, this extra line helped me a little, In this way you will have the dynamic numbering on the beginning:
// Hide all slides except first and add active class to first
slides.not(‘:first’).css(‘display’, ‘none’);
currentSlide.addClass(‘active’);
pager.text(currentSlideIndex+’ / ‘+slidesCount);
Thank you for sharing this example.
Only the demo button doesn’t work anymore.
Hey Tim, sorry, the links are fixed now. Thanks