Reputation: 2950
I'm trying to build a small slider in jquery, that autoplays and also has navigation buttons that allow to change the current slide. So far I managed to get the Buttons to work, but as I'm not very confident with JQuery I have no idea how to get the timed change to work.
I tried some suggestions I saw here on stackoverflow, like using setInterval and setTimeout, but I can not get it to work properly. My main problem is that I want to make sure the animations finish before the slide is changed per click and that a click resets the timer for the autoplay.
I hope someone here can help me with my problem.
Edit: I got a timer function to work, now my problem is that if you click a button while the animation is running, it might result in two slides being shown at the same time. How can I make sure the click is qued until the animations have finished playing?
Here is a fiddle: http://jsfiddle.net/9sgfd22r/10/
Here is my function:
(function($){
$.fn.Slider = function(interval) {
var slides = $sliderdiv.children('.slides');
var amount = slides.length;
var i = 0;
var animation = 0;
var clicked = 0;
function run() {
animation = 1;
$('.slides:visible').each(function() {
active = this.id.replace('slide', '');
active = active - 1;
console.log(active);
});
$(slides[active]).fadeOut(1000, function(){
i = clicked - 1;
$("img", $(slides[i])).each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
$(slides[i]).fadeIn(1000);
clicked = 0;
animation = 0;
intervaltint = setInterval(autoplay,3000);
});
}
function autoplay(){
console.log('running');
animation = 1;
$('.slides:visible').each(function() {
active2 = this.id.replace('slide', '');
active2 = active2 - 1;
console.log(active2);
});
$(slides[active2]).fadeOut(1000, function(){
active2++;
if (active2 >= amount) active2 = 0;
$("img", $(slides[active2])).each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
$(slides[active2]).fadeIn(1000);
animation = 0;
});
}
intervaltint = setInterval(autoplay,3000);
var $slidernav = $('.slidernav');
$('.slidernav').click(function() {
clearInterval(intervaltint);
activeslide = this.id.replace('slidernav', '');
if (animation == 0) {
clicked = activeslide;
run();
}
else {
console.log('not now');
clicked = activeslide;
run();
}
});
};
})(jQuery);
Upvotes: 0
Views: 1072
Reputation: 6722
how about this fiddle
Sample code which i have added is
function next(){
if (animation == 0) {
$('.slides').each(function(index,value) {
if($(this).is(':visible')){
if(($('.slides').length-1) == index){
clicked = 1;
}
else{
if(clicked == 0)
clicked++;
clicked++;
}
}
});
run();
}
}
$('#next').click(function(){
next();
});
Upvotes: 1