Search code examples
jqueryslideshowinfinite-loophorizontal-scrolling

Looping horizontally sliding divs infinitly


I have been trying to write my own carousal with infinite loop. The code works perfectly fine with one exception. I want to it go in loop where first divs gets appended in the last and so on. Right now it gets reset to previous position.

I have tried different things but none seems to work. Any help?

let divArray = $(".mybox");
let sliderFrame = $(".slider");
let i = 0;

function test() {
  //sliderFrame.append(divArray[i]);
  sliderFrame.delay(1000).animate({ right: 150 * i + "px" });
  if (i < divArray.length/2) i++;
  else i = 0;
  test();
}
test();

https://codepen.io/xblack/pen/mLYdeb

Solution

  • You might want to try this --

    let sliderFrame = $(".slider");
    let i = 0;
    
    function test() {
      let divArray = $(".mybox");
      $(divArray[0]) 
        .animate({"margin-left":"-150px"}, 5000, function() {
        $(this)
          .css({"width":"150px","margin-left":"0px"})
          .appendTo(sliderFrame);
        test();
      });
    }
    test();