2

I am working on the below demo. How can I enable previous button to slide to? As you can see the next button is working fine but I am not able to slide back.

$("#slideshow > div:gt(0)").hide();

$("#next").on("click", function() {
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
});

$("#prev").on("click", function() {
  $('#slideshow > div:prev')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
});
#slideshow {
  margin: 80px auto;
  position: relative;
  width: 240px;
  height: 240px;
  padding: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
}

#slideshow>div {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="next"> next</button>
<button id="prev"> prev</button>

<div id="slideshow">
  <div>
    <img src="http://farm6.static.flickr.com/5224/5658667829_2bb7d42a9c_m.jpg">
  </div>
  <div>
    <img src="http://farm6.static.flickr.com/5230/5638093881_a791e4f819_m.jpg">
  </div>
  <div>
    Pretty cool eh? This slide is proof the content can be anything.
  </div>
</div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

1 Answers1

1

Use a counter.

You cannot use the pseudo-class :prev selector because it does not exist

Is there a "previous sibling" CSS selector?

$(function() {
  $("#slideshow > div:gt(0)").hide();
  var $divs   = $('#slideshow > div'),
    nofSlides = $divs.length,
    counter   = 0;

  $(".but").on("click", function() {
    dir = $(this).is("#next") ? 1 : -1;
    $divs.eq(counter).stop().fadeOut(1000); // use stop to not queue
    counter += dir;
    if (counter >= nofSlides) counter = 0;
    if (counter < 0) counter = nofSlides - 1;
    $divs.eq(counter).stop().fadeIn(1000);
  });
});
#slideshow {
  margin: 80px auto;
  position: relative;
  width: 240px;
  height: 240px;
  padding: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
}

#slideshow>div {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="prev" class="but"> prev</button>
<button type="button" id="next" class="but"> next</button>
<div id="slideshow">

  <div>1
    <img src="http://farm6.static.flickr.com/5224/5658667829_2bb7d42a9c_m.jpg">
  </div>
  <div>2
    <img src="http://farm6.static.flickr.com/5230/5638093881_a791e4f819_m.jpg">
  </div>
  <div>3 Pretty cool eh? This slide is proof the content can be anything.
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236