Search code examples
javascriptjqueryjquery-selectors

jQuery slideshow, go to previous image


Trying to make the .next() work in reverse way, so it goes to the previous image in the slideshow instead of the next one, however, when I press the button it goes blank (nothing appears).

<div id="slider">
    <img src="slide1.png" class="sliderImage" />
    <img src="slide2.png" class="sliderImage" />
    <img src="slide3.png" class="sliderImage" />
</div>

<a href="javascript:void(0)"><div id="relative"><i class="fa fa-chevron-left" id="sliderArrowLeft"></i></div></a>
<a href="javascript:void(0)"><div id="relative"><i class="fa fa-chevron-right" id="sliderArrowRight"></i></div></a>

Script:

$('#slider img:gt(0)').hide();
        setInterval(function(){
          $('#slider :first-child').hide()
             .next('img').delay(1).fadeIn()
             .end().appendTo('#slider');},
          30000);

          $("#sliderArrowRight").click(function() {
              $('#slider :first-child').hide()
             .next('img').delay(1).fadeIn()
             .end().appendTo('#slider');
          });

          $("#sliderArrowLeft").click(function() {
              $('#slider :first-child').hide()
             .prev('img').delay(1).fadeIn()
             .end().appendTo('#slider');
          });

Any help is appreciated.


Solution

  • Your problem is prev('img') doesn't exists for the slider first child. So change your function like this :

    $("#sliderArrowLeft").click(function() {
        $('#slider :first-child').hide();
        $('#slider :last-child').delay(1).fadeIn().prependTo('#slider');
    });