user3371372
user3371372

Reputation: 35

jQuery slider - prev and next issue

I'm trying to make a simple slider with prev and next buttons. If go a step forward and than backward i don't get always the previous image . I have noticed that the next and prev button don't use the same index but I don't know how to fix that.

   $("img").hide();
    $("img").first().show();

    var currentItem = $("img").first().next().index();
    var lastItem = $("img").last().index();


    $('#next').click(function(){
        $("img").hide();
        $("img").eq(currentItem).show();
        if(currentItem == lastItem){
            currentItem = 0;
        }else{
            currentItem = $("img").eq(currentItem).next().index();
        }
    });


   var currentItem2 = $("img").last().prev().index();

    $('#prev').click(function(){
        $("img").hide();
        $("img").eq(currentItem2).show();
        if( currentItem2 == lastItem ){
            currentItem2 = 2;
        }else{
            currentItem2 = $("img").eq(currentItem2).prev().index();

        }
    });

This is my html code

 <div id="slider">

    <img src="bilder/walle.jpg" alt=""/>
    <img src="bilder/up.jpg" alt=""/>
    <img src="bilder/toystory.jpg" alt=""/>
    <img src="bilder/nemo.jpg"alt=""/>

    <div id="next">Next</div>
    <div id="prev">prev</div>
</div>

Upvotes: 1

Views: 2798

Answers (2)

Adrien0
Adrien0

Reputation: 79

Just by modifying a bit Trevor's code, you could have something like that:

var images = [];
$('#slider img').each(function () {
    images.push($(this));
    $(this).hide();
});

var imgcount = images.length;
var currentItem = 0;
images[currentItem].show();

$('#next').click(function () {
    images[currentItem].hide();
    currentItem = (currentItem + 1) % imgcount;
    images[currentItem].show();
});

$('#prev').click(function () {
    images[currentItem].hide();
    if (currentItem > 0)
        currentItem--;
    else
        currentItem = imgcount - 1;
    images[currentItem].show();
});

Then your code still works if you want to add new images, and you will not hide all the images of your web page each time you click next or previous :)

http://jsfiddle.net/wmxzK/4/

Upvotes: 2

Trevor
Trevor

Reputation: 16116

Here is one way to do it:

var images = [];
$('#slider img').each(function(){
    images.push($(this));    
});
var imgcount = images.length;
$("img").hide();
$("img").first().show();
var currentItem = 0;

$('#next').click(function(){
        $("img").hide();
        currentItem++;
        images[currentItem%4].show();        
});

$('#prev').click(function(){
        $("img").hide();
       currentItem--;
       if(currentItem < 0)
           currentItem = imgcount-1;
       images[currentItem%4].show();
});

Fiddle:

http://jsfiddle.net/wmxzK/

Upvotes: 0

Related Questions