Setting a timer in jQuery/javascript
I have a picture slideshow that works on a click of a butt开发者_运维技巧on like so: ">". The button is a span with id "slideshowRight".
Is it possible to set a timer that every 5 seconds literally clicks the slideshowRight button and stops when the mouse hovers over the buttons and restarts when the mouse doesn't hover on them?
The hover-stop is not as crucial as the every 5-second click. I know jQuery has a .click() function.
Thanks, Amit
check the setTimeout and setinterval functions. something like this should click it ever 5 seconds:
setInterval(function(){
$("myButton").click();
}, 5000);
You then could clear and start the interval when the user hovers in and out, using the above and the clearInterval
function
Shouldn't it be called slideshowLeft
? Oh well,
If you have a button, then:
slideshowRight.click(function() {
// do some stuff
});
you could actually trigger a click of that button by script:
slideshowRight.trigger('click');
but I'd argue it'd be neater to simply refactor the function:
slideshowRight.click(slideshowRight_click);
function slideshowRight_click() {
// do some stuff
}
Based on that, you could set an interval to the following:
var isHover = false;
setInterval(function() {
if(isHover) return; // do nothing!
slideshowRight_click();
}, 5000); // every 5 sec
And you could change the value of isHover
like so:
slideshowRight.hover(function() { isHover = !isHover; });
Hover will be called once on hover, and once again when the user stops hovering the button, and its value will be set to whatever it wasn't at the moment.
精彩评论