Search code examples
jquerysliderlogicinfinite-scrolljquery-ui-slider

Jquery simple infinite loop slider logic


I'm new to Jquery and making a simple static slider with five images of same class name (.sl_thumb) This is code on Next and Previous Anchor -- Right Anchor (.right_nav_link), Left Anchor (.left_nav_link) Main Div of slide(.slide_container)

My previous and Next Links are working fine but when slider reaches to last slide it stops, I am trying to make infinite looping slider, so that it should again reach to first slide after last. As a beginner, I've tried many things but confused, what can be the best possible logic I can use.

$(document).ready(function () {
    var src = 'img/img1.jpg';
    $(".right_nav_link").click(function () {
        var next = false;
        $($("img").filter(".sl_thumb")).each(function (key, value) {
            if ($(this).attr('src') == src) {
                next = true;
            } else if (next) {
                next = false;
                src = $(this).attr('src');
                $(".slide_container").css('background-image', 'url(' + src + ')');
                return;
            }
        });
    });
$(".left_nav_link").click(function () {
        var prev = false;
        $($("img").filter(".sl_thumb").get().reverse()).each(function (key, value) {
            // console.log(key,value);
            if ($(this).attr('src') == src) {   
                prev = true;
            } else if (prev) {
                prev = false;
                src = $(this).attr('src');
                $(".slide_container").css('background-image', 'url(' + src + ')');
                return;
            }
        });
    });
});


Solution

  • $( document ).ready(function() {
      var src = 'img/img1.jpg';
      
      function adjustSlideContainer ( adjustPositionAmount ) {
        //get all the images
        var $thumbnails = $( 'img.sl_thumb' );
        //find the current one shown
        var $current = $thumbnails.filter( '[src="'+ src +'"]' );
        //get its index
        var currentIndex = $thumbnails.index( $current );
        //adjust the index to the image that should be shown next
        var nextIndex = currentIndex + adjustPositionAmount;
        
        if ( nextIndex < 0 ) {
          //if it's before the first one, wrap to the last one
          nextIndex = $thumbnails.length - 1;
        } else if ( nextIndex >= $thumbnails.length ) {
          //if it's after the end one, wrap to the first one
          nextIndex = 0;
        }
        
        src = $thumbnails.eq( nextIndex ).attr( 'src' );
        $( '.slide_container' ).css( 'background-image', 'url(' + src + ')' );
      }
      
      $(".right_nav_link").click(function() {
        //go to the next image
        adjustSlideContainer( 1 );
      });
      
      $(".left_nav_link").click(function() {
        //go to the previous image
        adjustSlideContainer( -1 );
      });
    });