Amit
Amit

Reputation: 7838

Setting a timer in jQuery/javascript

I have a picture slideshow that works on a click of a button 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

Upvotes: 2

Views: 8794

Answers (2)

Tim Büthe
Tim Büthe

Reputation: 63814

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

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129832

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.

Upvotes: 0

Related Questions