Dave
Dave

Reputation: 61

Stop js slideshow caching amount of clicks

Does anyone know how to stop this slideshow from 'caching' the amount of clicks through the slides? If I click the arrows 10 times then 10 slides will slide through is there a way to stop this? Or alternatively if you click the opposite arrow for it to cancel the 'cached' clicks from the other?

http://www.switchonthecode.com/tutorials/jquery-creating-a-slideshow

Thanks!

Upvotes: 0

Views: 134

Answers (2)

riwalk
riwalk

Reputation: 14233

Using the one() function will probably do what you are looking for. Adjust the code to the following:

$(document).ready(function(){
    // The "one()" function means that this action is disconnected
    // from the element once the action occurs. In other words, click
    // it twice, and the second one does nothing.
    $("#slideshow-previous").one("click", showPreviousSlide);
    $("#slideshow-next").one("click", showNextSlide);
    ...
});

However just doing that isn't enough. We have to hook up the event handler again after the animation is finished. Use the callback function for animate():

function updateContentHolder()
{
    ...
    $("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
        $("#slideshow-previous").one("click", showPreviousSlide);
        $("#slideshow-next").one("click", showNextSlide);
    });
}

As was pointed out in the comments this has the problem of attaching showPreviousSlide and showNextSlide multiple times to whichever button was not pressed. You can remedy this by doing just a little more work:

function showPreviousSlide()
{
    currentSlide--;
    updateContentHolder($(this).attr("id"), showPreviousSlide);
    updateButtons();
}

function showNextSlide()
{
    currentSlide++;
    updateContentHolder($(this).attr("id"), showNextSlide);
    updateButtons();
}

...

function updateContentHolder(id, callback)
{
    ...
    $("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
        $("#" + id).one("click", callback);
    });
}

Upvotes: 1

James Montagne
James Montagne

Reputation: 78630

You could set a flag to true whenever an arrow is clicked something like isPending. Then check this whenever an arrow is clicked and if it is true, ignore the click. Then when the animation finishes set the flag back to false.

Upvotes: 0

Related Questions