Lightweight Automatic Content Slider with jQuery

Lightweight Automatic Content Slider with jQuery
File Size: 2.44 KB
Views Total: 671
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A basic, lightweight jQuery slider that automatically cycles through a set of Html content with support of pause of hover.

How to use it:

1. Create a content slider from an unordered list of Html content.

<div id="slider">
  <ul class="slides">
    <li class="slide"><img src="1.png"></li>
    <li class="slide"><img src="2.png"></li>
    <li class="slide"><img src="3.png"></li>
    <li class="slide"><img src="4.png"></li>
    <li class="slide"><img src="5.png"></li>
    ...
  </ul>
</div>

2. The required slider styles.

#slider {
  width: 600px;
  height: 300px;
  overflow: hidden;
  margin-top: 50px;
  margin-left: auto;
  margin-right: auto;
}

#slider .slides {
  display: block;
  width: 3600;
  height: 300px;
  margin: 0;
  padding: 0;
}

#slider .slide {
  float: left;
  list-style-type: none;
  width: 600px;
  height: 300px;
}

3. Load the needed jQuery JavaScript library in your document.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

4. Enable the content slider with a little bit JavaScript.

$(document).ready(function() {

  //configuration
  var width = 600;
  var animationSpeed = 1000;
  var pause = 2500;
  var currentSlide = 1;

  //cache DOM - very efficient code. Only searching the DOM for #slider.
  var $slider = $("#slider");
  var $slideContainer = $slider.find('.slides');
  var $slides = $slideContainer.find('.slide');
  var interval;

  //mouse enters the slider
  $slider.on("mouseenter", pauseSlider).on("mouseleave", startSlider);

  //start slider function
  function startSlider() {
    interval = setInterval(function(){
      $slideContainer.animate({
        "margin-left": "-="+ width +"px"},
        animationSpeed, function() {
        currentSlide ++;
        if (currentSlide == $slides.length) {
          currentSlide = 1;
          $slideContainer.css("margin-left", 0);
        }
      });
    }, pause);
  };

  //stop slider function
  function pauseSlider() {
    clearInterval(interval);
  }

  //call the startslider function to start the slider.. duh
  startSlider();

});

This awesome jQuery plugin is developed by kineticR. For more Advanced Usages, please check the demo page or visit the official website.