I'm working on a simple slider carousel and I need that when there is no previous or next item you can not move to a nonexistent element like this is happening, link
I'm working on a simple slider carousel and I need that when there is no previous or next item you can not move to a nonexistent element like this is happening, link
I think it has a more optimized form, but it works perfectly.
var sliderWidth = 300;
var slider = $('#slider');
var sliderCount = $('div', slider).length;
var cont =1;
$(document).ready(function() {
var numItems = $('.sliderItem').length;
$('.date-nav-prev').hide();
});
slider.width(sliderCount * sliderWidth);
$('.date-nav-prev').click(function () {
$('#slider').animate({left: '+='+sliderWidth}, 500);
cont--;
hidePrev();
hideNext();
});
$('.date-nav-next').click(function () {
$('#slider').animate({left: '-='+sliderWidth}, 500);
cont++;
hidePrev();
hideNext();
});
function hideNext(){
if(cont==sliderCount){
$('.date-nav-next').hide();
}else{
$('.date-nav-next').show();
}
}
function hidePrev(){
if(cont>1){
$('.date-nav-prev').show()
}else{
$('.date-nav-prev').hide()
}
}
HTML
<button class="date-nav-prev">< Prev</button>
<button class="date-nav-next">Next ></button>
<div id="wrapper">
<div id="slider">
<div class="sliderItem" id="today">Today's Actions</div>
<div class="sliderItem" id="today">Today's Actions</div>
<div class="sliderItem" id="today">Today's Actions</div>
</div>
</div>
jQuery
$(document).ready(function () {
var sliderWidth = 300;
var slider = $('#slider');
var sliderCount = $('div', slider).length;
var numItems = $('.sliderItem').length;
if (numItems <= 1) {
$('.date-nav-prev').hide();
$('.date-nav-next').hide();
}
var numItems = $('.sliderItem').length;
slider.width(sliderCount * sliderWidth);
var counter = 0;
$('.date-nav-prev').click(function () {
if (counter > 0) {
counter--;
$('#slider').animate({ left: '+=' + sliderWidth }, 500);
}
});
$('.date-nav-next').click(function () {
counter++;
if (counter < numItems) {
$('#slider').animate({ left: '-=' + sliderWidth }, 500);
}
else {
counter = 0;
$('#slider').animate({ left: '+=' + sliderWidth * sliderCount - 150 }, 500);
}
});
});
Total Update:
Just control the current slide, and do not let go before 1 or after the number of slides:
var sliderWidth = 300;
var slide = 1;
var slider = $('#slider');
var sliderCount = $('div', slider).length;
slider.width(sliderCount * sliderWidth);
$('.date-nav-prev').click(function () {
if (slide > 1) {
slide--;
slider.animate({ left: '+=' + sliderWidth }, 500);
}
});
$('.date-nav-next').click(function () {
if (slide < sliderCount) {
slide++;
slider.animate({ left: '-=' + sliderWidth }, 500);
}
});