Nico
Nico

Reputation: 1081

jquery image slider with .next() and .prev() not working

Iam trying to code an simple image slider with next and prev buttons. But I have problems iterating through the list, especially when its the first image and I click the prev button. The slider should then show the last image. Maybe someone can give me a hint...

My HTML:

<div id="slideshow"> 
<img src="img/slide11.jpeg"  alt="" class="active">
<img src="img/slide31.png" alt="">
<img src="img/slide21.png"  alt="">
</div>

Click Handler:

$(document).ready(function () {
 $('#next').bind('click', function() {
    slideSwitchP('next');
});

 $('#prev').bind('click', function() {
    slideSwitchP('prev');
});
});
}

And the jQuery Code so far (not working)

function slideSwitchP($control) {
var $active = $('#slideshow IMG.active');

var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first');
var $prev = $next.prev().length ? $active.prev() : $('#slideshow IMG:last');

console.log('next', $next);
console.log('prev', $prev);

$active.addClass('last-active');

if($control === 'next'){ 
console.log($control);
$next.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 1000, function() {
        $active.removeClass('active last-active');
    });
}
if($control === 'prev'){ 
console.log($control);
//prev not working!
}
}

Any ideas will be appreciated! Thanks!

Upvotes: 1

Views: 1676

Answers (1)

Engineer
Engineer

Reputation: 48793

I think, you need this:

var $prev = $active.prev().....
           //  ^---------instead of `$next`

Live demo

Upvotes: 1

Related Questions