5

I am writing a simple fade-slideshow with previous and next buttons.

The problem is that when I click the next button very quickly (for example 2 times), before the first event finished, the second one will be executed, so for less than a second I will see, two images in my page.

    $("#next_button").click(function (){
        $("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
            current_slide ++;
            current_slide = current_slide % slides_number;
            $("#slide"+current_slide).fadeIn(FADE_DURATION, function (){
                $(".slide_image").not("#slide"+current_slide).attr("style", "display: none;");
            });
        });
    });
  • In the last line, after fadeIn(), I even tried to hide everything except current image, wishing the issue will be solved, but that doesn't work.

  • I read something about event.stopImmediatePropagation() but I couldn't use it, or maybe it wasn't my solution.

How to force jQuery to ignore executing any similar events, before one of those same events, get finished?

Milad R
  • 1,854
  • 9
  • 25
  • 36

2 Answers2

3

You can add a flag that indicates when your slider is in the middle of transitioning:

var isSliding = false;

$("#next_button").click(function (){

  if(isSliding) {
    return false;
  }

  isSliding = true;

    $("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
        current_slide ++;
        current_slide = current_slide % slides_number;
        $("#slide"+current_slide).fadeIn(FADE_DURATION, function (){
            $(".slide_image").not("#slide"+current_slide).attr("style", "display: none;");

            isSliding = false;
        });
    });
});
Mario Pabon
  • 605
  • 4
  • 8
  • 1
    I can't believe it was that simple! I thought it must be something complicated related to event handling, which I don't know anything about it. :) – Milad R Sep 10 '15 at 22:17
  • 1
    You can accomplish this with binding/unbinding of events too, but it's a bit more complicated. As another answerer mentioned, you can check out those solutions here: http://stackoverflow.com/questions/1921855/jquery-how-can-i-temporarily-disable-the-onclick-event-listener-after-the-even And if you want to learn more about event binding in jQuery you can read up about it in the jQuery API docs: http://api.jquery.com/on/ – Mario Pabon Sep 10 '15 at 22:40
1

You can bind and unbind, but it is time consumer if you repeat it a lot, if yo neet to fo it more than few times try to look into this answer: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

Community
  • 1
  • 1
Alonline
  • 11
  • 2