Jacob Solano
Jacob Solano

Reputation: 1

jquery image slider: reach last image, must click 'next' to go back to first

I have used the nivo slider and a few others. Editing those aren't a problem. This time I am trying to create my own simple slider on my own. I can have images fade in/out into one another, but after the final image - it fades out into nothing and I need to figure out how to make it simply reset to the first image. Currently i am only using 'next' and i'm sure once I have that done, i can figure out the 'previous' button.

I've tried an if statement but can't quite get there. I've torn this down to bare minimums to try and get things easy to read. Appreciate any help.

Here is all of my code:

CSS:

p {margin: 0; padding: 0}

.slides{
width: 500px; height: 200px;
position: relative;
margin: 20px auto;
overflow: hidden;
}

.img1, .img2, .img3 {
width: 500px; height: 200px;
display: block;
position: relative;
float: left;
}

.img1 {background-image: url(img1.png)}
.img2 {background-image: url(img2.png)}
.img3 {background-image: url(img3.png)}

.title {
width: 480px; height: 30px;
color: white; font-size: 15px;
padding: 10px;
position: absolute; top: 0;
background: url(tbg.png) 0 0 repeat;
}

.description {
width: 480px; height: 30px;
color: white; font-size: 15px;
padding: 10px;
position: absolute; bottom: 0;
background: url(tbg.png) 0 0 repeat;
}

.prev, .next {
width: 50px; height: 50px;
position: absolute; z-index: 10;
top: 50px; display: block;
background: url(prevnext.png) 0 0 no-repeat;
border: none; cursor: pointer;
}

.active{top: 0; left: 0}


.prev {left: 20px}
.next {right: 20px; background-position: -50px 0}

#img:not(.active) {display:none}

jquery:

$(function() {
$('#next').click(function(event) {
    $('#slides .active').fadeOut('slow').removeClass('active')
    .next('#img').fadeIn('slow').addClass('active');

});
});

HTML:

<div id="slides" class="slides">
    <div id="img" class="img1 active">
        <div class="title"><p>This Is My Title</p></div>
        <div class="description"><p>This Is My Description</p></div>
    </div>
    <div id="img" class="img2">
        <div class="title"><p>This Is My Title</p></div>
        <div class="description"><p>This Is My Description</p></div>
    </div>
    <div id="img" class="img3">
        <div class="title"><p>This Is My Title</p></div>
        <div class="description"><p>This Is My Description</p></div>
    </div>
    <a id="prev" class="prev"></a>
    <a id="next" class="next"></a>
</div>

Upvotes: 0

Views: 1816

Answers (1)

techfoobar
techfoobar

Reputation: 66663

Try this:

$('#next').click(function(event) {
    var active = $('#slides .active');
    active.fadeOut('slow').removeClass('active');
    if(active.next('#img').length != 0)
        active.next('#img').fadeIn('slow').addClass('active');
    else
        $('#slides #img:first').fadeIn('slow').addClass('active');
});

Upvotes: 1

Related Questions