user7548524
user7548524

Reputation: 53

temporarily stopping function jquery

var start = $('#start_img');

start.on('click', function(){
    var piano = $('.piano');
    piano.each(function(index){
        $(this).hide().delay(700 * index).fadeIn(700*index);
        start.off('click');
    })

});

You can see that I have used the start.off('click') method, to stop the Event Listener from running again once it has been called. But the thing is, I only want the Event listener to be off during the time that the event is running. So that it cannot be called again while the event is still running. But once the event has finished, I want it to be 'callable' again. Does anyone know how t do this?

other way of doing this (doesn't work neither). Can anyone help me here. The other one is now clear.

var start = $('#start_img');



    start.on('click', function() {
      var q = 0;
      var piano = $('.piano');
      if (q === 1) {
        return; // don't do animations
      }
      else{
        piano.each(function(index) {
        q = 1;
        $(this).hide()
               .delay(700 * index)
               .fadeIn(700 * index, function() {
                    // remove from each instance when animation completes
                    q = 0
                });

      });}

    });

Upvotes: 0

Views: 56

Answers (2)

Mateus
Mateus

Reputation: 5382

For only one object, you could use a global variable for this, in my case, I'll be using isRunning:

var start = $('#start_img');
var isRunning = false;

start.on('click', function(){
    if (!isRunning){
        isRunning = true;
        var piano = $('.piano');
        piano.each(function(index){
            $(this).hide().delay(700 * index).fadeIn(700*index, function(){
                isRunning = false;
            });
            start.off('click');
        });
    }
});

This way your app shouldn't run the code until isRunning == false, which should happen after fadeIn is completed.

Syntaxes:

.fadeIn([duration] [,complete]);
.fadeIn(options);
.fadeIn([duration] [,easing] [,complete]);

For two or more objects, Charlietfl's answer should work perfectly.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

You could toggle a class on active elements as well and then you can check for that class and not do anything if it exists

start.on('click', function() {
  var piano = $('.piano');
  if (piano.hasClass('active')) {
    return; // don't do animations
  }
  piano.each(function(index) {
    $(this).addClass('active')
           .hide()
           .delay(700 * index)
           .fadeIn(700 * index, function() {
                // remove from each instance when animation completes
                $(this).removeClass('active')
            });

  });

});

Upvotes: 2

Related Questions