Skip to content Skip to sidebar Skip to footer

How To Wait For A Jquery Toggle To Finish Before Running Another Function?

I am missing something really obvious but I can't make one of my methods to wait until a jQuery toggle is done. I have the following three methods: const toggleContainer = functio

Solution 1:

.toggle( [duration ] [, complete ] )

The optional second argument is the function to cal once the animation is done, so just call toggle with the desired callback. Promises are the best way to do something like this:

consttoggleContainer = () => newPromise(resolve =>
  addAnswerContainer.toggle("slow", resolve)
);

consttoggleButtons = () => newPromise(resolve => {
    submitAnswerBtn.toggle("slow");
    cancelAnswerBtn.toggle("slow", resolve);
});

const changeText = function() {
  if( addAnswerContainer.is(":hidden") ) {
    addOwnAnswerBtn.text("Add your own answer" );
  }
  else {
    addOwnAnswerBtn.text("Hide adding answer");
  }
};

Then call .then on the promises to chain asynchronous functions:

const toggleUI = function() {
  toggleContainer()
    .then(toggleButtons)
    .then(changeText);
};

Or if you want toggleContainer and toggleButtons to run at once, and only wait before changeText:

const toggleUI = function() {
  toggleContainer()
  toggleButtons()
    .then(changeText);
};

Solution 2:

I may suggest a simple but smart approach following your if-else statements like so:

const toggleContainer = function() {
  addAnswerContainer.toggle("slow");
  returntrue;
};

const toggleButtons = function() {
  submitAnswerBtn.toggle("slow");
  cancelAnswerBtn.toggle("slow");
};

constToggleIfTrue = () => {
  if(addAnswerContainer.is(":hidden") && toggleContainer) { 
    addOwnAnswerBtn.text("Add your own answer" );
  }
  elseif (addAnswerContainer.is(!":hidden") && toggleContainer) {
    addOwnAnswerBtn.text("Hide adding answer");
  }
};

So this way the inner if-else statement only runs if the addAnswerContainer is set as hidden and the other way around with the final else if statement

Solution 3:

Can return $.when promise from the toggle function and use promise() of element objects to be resolved in $.when.

call next step in next then() of promise chain

Simplified demo

const toggleComplete = function(){
   console.log('finished animation id #', this.id)
}

const toggleButtons = function (){
  // toggleComplete only needed for this demolet p1=$('#1').toggle('slow',toggleComplete).promise()
  let p2=$('#2').toggle('slow',toggleComplete).promise()
 
  return $.when(p1,p2)
}

toggleButtons().then(_=>console.log('all animations done')/* change text here*/)
div{display:none}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="1">
One
</div><divid="2">
Two
</div>

Post a Comment for "How To Wait For A Jquery Toggle To Finish Before Running Another Function?"