jQuery multiple content sliders?

jQuery multiple content sliders?

How can I change the jQuery code below to have multiple content sliders working? When I try and add additional sliders it doesn't work correctly.

CodePen https://codepen.io/anon/pen/aKPReW

Any help is much appreciated. Thanks in advance!


jQuery

  1. var allSlides = $('.slide');
            var activeSlide = 0;

  2. setInterval('autoSlide()', 4000);

  3. $(".slider-next").click(function() {
  4.   if (activeSlide+1 >= allSlides.length) {
  5. allSlides.eq(activeSlide).removeClass("active");
  6. activeSlide = 0;
  7. allSlides.eq(0).addClass("active");
  8.   }
  9.   else {
  10. allSlides.eq(activeSlide).removeClass("active");
  11. activeSlide++;
  12. allSlides.eq(activeSlide).addClass("active");
  13.   }
  14. });
  15. $(".slider-prev").click(function() {
  16.   if (activeSlide-1 < 0) {
  17. allSlides.eq(0).removeClass("active");
  18. activeSlide = allSlides.length-1;
  19. allSlides.eq(activeSlide).addClass("active");
  20.   }
  21.   else {
  22. allSlides.eq(activeSlide).removeClass("active");
  23. activeSlide--;
  24. allSlides.eq(activeSlide).addClass("active");
  25.   }
  26. });

  27. function autoSlide() {
  28. if (activeSlide+1 >= allSlides.length) {
  29.   allSlides.eq(activeSlide).removeClass("active");
  30.   activeSlide = 0;
  31.   allSlides.eq(0).addClass("active");
  32. }
  33. else {
  34.   allSlides.eq(activeSlide).removeClass("active");
  35.   activeSlide++;
  36.   allSlides.eq(activeSlide).addClass("active");
  37. }
  38. }


HTML

  1. <html>
  2. <body>    
  3. <div>
  4.         <div class="slider-btn">
  5.             <button class="slider-prev"><</button>
  6.             <button class="slider-next">></button>
  7.         </div>
  8.         <div class="slider">
  9.             <div class="slide active">
  10.                 <h2>Slide 1</h2>
  11.             </div>
  12.             <div class="slide">
  13.                 <h2>Slide 2</h2>
  14.             </div>
  15.         </div>
  16.     </div>
  17. </body>
  18. </html>

CSS

  1. .slider {
  2.   position: relative;
  3.   width: 80%;
  4. }

  5. .slide {
  6.     position: absolute;
  7.     opacity: 0;
  8. }

  9. .active {
  10.     transition: opacity 500ms ease;
  11.     opacity:1;
  12. }