0

Good day fellow coders,

After tinkering awhile, I still couldn't find a way to invoke visual effects in jQuery and trigger a function afterwards. The program either completes mere visual effects, such as a vertical flip, or solely executes the denoted function. Is there a way to firstly complete the graphical effects and trigger the included function lastly, in just one click? Below the pertaining code:

$("#HTMLButton").click(function(){
            $("#Div").slideUp(400); //Is only run
            arbitraryFunction; //Ignored 
        });

  $("#HTMLButton").click(function(){
                arbitraryFunction; //Is only run
                $("#Div").slideUp(400); //Ignored
            });

Thank you in advance!

Jelle 3.0
  • 11
  • 4
  • Does this answer your question? [jQuery - Wait till end of SlideUp()](https://stackoverflow.com/questions/1084392/jquery-wait-till-end-of-slideup) – Don't Panic May 17 '20 at 23:51

1 Answers1

0

First thing to do is have a look at the jQuery docs - https://api.jquery.com/slideUp/

.slideUp( [duration ] [, complete ] )

duration (default: 400)

  • Type: Number or String
  • A string or number determining how long the animation will run.

complete

  • Type: Function()
  • A function to call once the animation is complete, called once per matched element.

So rather than a Promise interface, they offer a more traditional callback interface

$("#HTMLButton").click(function(){
    $("#Div").slideUp(400, () => {
        arbitraryFunction()
    });
});

An alternative approach (if you lacked a callback mechanism) would be a setTimeout() function:

$("#HTMLButton").click(function(){
    $("#Div").slideUp(400);
    setTimeout(() => {
        arbitraryFunction();
    }, 400);
});
James McGuigan
  • 7,542
  • 4
  • 26
  • 29
  • Thanks for your quick reply, the second solution was exactly what I needed to get the code running. Without this answer, solving the problem would have probably been impossible, again, thank you. – Jelle 3.0 May 19 '20 at 07:35
  • With the `setTimeout()` option, also experiment with setting a timeout of 0. The way the javascript event loops work, is that a setTimeout(0) will add the function to the end of the event loop and call it once the existing thread has finished. This changes the order of events, and your second function might be depending on a DOM manupulations caused by jQuery, which might itself be using setTimeout(). – James McGuigan May 19 '20 at 19:58