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
- var allSlides = $('.slide');
var activeSlide = 0;
- setInterval('autoSlide()', 4000);
- $(".slider-next").click(function() {
- if (activeSlide+1 >= allSlides.length) {
- allSlides.eq(activeSlide).removeClass("active");
- activeSlide = 0;
- allSlides.eq(0).addClass("active");
- }
- else {
- allSlides.eq(activeSlide).removeClass("active");
- activeSlide++;
- allSlides.eq(activeSlide).addClass("active");
- }
- });
- $(".slider-prev").click(function() {
- if (activeSlide-1 < 0) {
- allSlides.eq(0).removeClass("active");
- activeSlide = allSlides.length-1;
- allSlides.eq(activeSlide).addClass("active");
- }
- else {
- allSlides.eq(activeSlide).removeClass("active");
- activeSlide--;
- allSlides.eq(activeSlide).addClass("active");
- }
- });
- function autoSlide() {
- if (activeSlide+1 >= allSlides.length) {
- allSlides.eq(activeSlide).removeClass("active");
- activeSlide = 0;
- allSlides.eq(0).addClass("active");
- }
- else {
- allSlides.eq(activeSlide).removeClass("active");
- activeSlide++;
- allSlides.eq(activeSlide).addClass("active");
- }
- }
HTML
- <html>
- <body>
- <div>
- <div class="slider-btn">
- <button class="slider-prev"><</button>
- <button class="slider-next">></button>
- </div>
- <div class="slider">
- <div class="slide active">
- <h2>Slide 1</h2>
- </div>
- <div class="slide">
- <h2>Slide 2</h2>
- </div>
- </div>
- </div>
- </body>
- </html>
CSS
- .slider {
- position: relative;
- width: 80%;
- }
- .slide {
- position: absolute;
- opacity: 0;
- }
- .active {
- transition: opacity 500ms ease;
- opacity:1;
- }