Ryan Copeland Ryan Copeland - 6 months ago 14
Javascript Question

image carousel won't infinitely loop in reverse

I am creating an HTML5 image carousel with three images. The transitions are done with TweenMax and TimeLine. I have two click events, one for next image and one for previous image, the next image function runs properly and is an infinite loop but the previous function stops after it goes through the images once. here is the code.

HTML:

<div id="expanded-state">
<div id="expanded-exit"></div>
<div id="close-btn"></div>
<button id="arrow-prev"></button>
<button id="arrow-next"></button>
<div id="theater">
<div class="theater"></div>
<div class="theater"></div>
<div class="theater"></div>
</div>
<div id="cta"></div>
<div id="footer"></div>
</div>
</div>


CSS:

.theater {
width: 970px;
height: 345px;
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}

.theater:nth-child(1){
background: url(theater-01.jpg);
}

.theater:nth-child(2){
background: url(theater-02.jpg);
}

.theater:nth-child(3){
background: url(theater-03.jpg);
}


JS:

var $slides = $(".theater");
var currentSlide = 0;

function addListeners() {
arrowPrev.addEventListener('click', theaterScrollPrev);
arrowNext.addEventListener('click', theaterScrollNext);
}

function theaterScrollNext() {

tm.to( $slides.eq(currentSlide), 0.5, {left:"-970px"} );

if (currentSlide < $slides.length - 1) {
currentSlide++;
}
else {
currentSlide = 0;
}

tm.fromTo( $slides.eq(currentSlide), 0.5, {left: "970px"}, {left:"0px"} );
}

function theaterScrollPrev() {

tm.to( $slides.eq(currentSlide), 0.5, {left:"970px"} );

if (currentSlide < $slides.length - 1) {
currentSlide--;
}
else {
currentSlide = 0;
}

tm.fromTo( $slides.eq(currentSlide), 0.5, {left: "-970px"}, {left:"0px"});
}

Answer

I believe this should fix it but tell me if it does not

    function theaterScrollPrev() {
    console.log('previous clicked')
    tm.to( $slides.eq(currentSlide), 0.5, {left:"970px"} );     

    if (currentSlide <= 0) {
        currentSlide = $slides.length -1;
  } else {
    currentSlide--;
    }

      tm.fromTo( $slides.eq(currentSlide), 0.5, {left: "-970px"}, {left:"0px"} );
}

Codepen Fixed

Comments