Reputation: 31
I have a jQuery script sliding through a few divs. The code is below. I have two issues I need to resolve:
Resetting or adding to the timer when a user clicks on a tab. At the moment, it may switch immediately to the next slide depending on where it is in the cycle.
Pausing the timer (i.e., clearing the timeout then restarting it) when a user is hovering over a particular slide.
To accomplish these, I gave setTimeout a variable ($theTimeout) and attempted to clearTimeout and then run show_cycle_elem() again. No matter how many different ways I tried to do it (by throwing my other events, such as the click, into functions, then calling them immediately after setTimeout, etc.), it didn't seem to work entirely right.
Any ideas?
$(document).ready( function(){
var theId = 0;
function navClass(it){
$('#hero nav a').removeClass('over');
$(it).addClass('over');
}
$.fn.cycle = function(timeout){
var $all_elem = $(this);
show_cycle_elem = function(){
if(theId == $all_elem.length) theId = 0;
$all_elem.hide().eq(theId).fadeIn();
navClass('#a' + theId);
var $theTimeout = setTimeout(function(){show_cycle_elem(++theId)}, timeout);
}
show_cycle_elem();
}
$('div.hero_slide').cycle(10000);
$('#hero nav a').click( function(party){
party.preventDefault();
theId = this.id.substr(1);
navClass($(this));
$('.hero_slide').hide();
$('#hero' + theId).fadeIn();
});
});
Thanks.
Upvotes: 0
Views: 837
Reputation: 9567
Hah looks like your trying to build a fluid slider with a few options... I had just that idea some months ago, figures this isn't actually as easy as it seems. For starters we're using jQuery so we might as well write it in a plugin format since we'll need a scope in which we can declare and use variables that change over time at will...
I'll just cut to the chase; if you want to work with slides / pause them you need to be in control of the timeout id, store it and clear the timeout when needed to prevent the next slide animation...
Took me some figuring out but heres my working version having only some very basic functionality but you can at least start / stop it and do next/prev/rand:
http://jsfiddle.net/sg3s/RFJMy/218/
So if you want to make a plugin/functionality that does the things you describe you will need to rewrite a good part of your code to have a base that can actually handle interrupts in a logical sense.
Upvotes: 1