How can I execute code after animation of hiding sidebar?

Viewed 139

Let's assume that I have a function like shown below. I want to execute this.sidebarVisible = false; after all the animations associated with the code shown above in sidebarClode() will be done. Any ideas how can I do this?

ts:

  sidebarOpen() {
    const toggleButton = this.toggleButton;
    const html = document.getElementsByTagName('html')[0];

    setTimeout(function () {
      toggleButton.classList.add('toggled');
    }, 500);
    html.classList.add('nav-open');

    this.sidebarVisible = true;

  };

  sidebarClose() {
    const html = document.getElementsByTagName('html')[0];
    this.toggleButton.classList.remove('toggled');
    html.classList.remove('nav-open');

    this.sidebarVisible = false; // I want to execute this line of code after all the animations associated with the code shown above in sidebarClode() will be done. I mean three lines of code above this comment.
  };

  sidebarToggle() {

    if (this.sidebarVisible === false) {
      this.sidebarOpen();
    } else {
      this.sidebarClose();
    }
  };

html:

  <button style="right: 1vw;" class="navbar-toggler navbar-burger" type="button" data-toggle="collapse" data-target="#navbarToggler"
          aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"
          (click)="sidebarToggle()" (transitionend)="this.printText()" >
1 Answers

Using CSS to do the animations like you seem to be doing, I'm not sure you can get this to work precisely since there is no animation complete callback method with CSS obviously.

You could guesstimate it using setTimeout but this would not be precise. You could also use polling. Let's say for example, you know that opacity will be 0 for your element when the animation is complete, you could use setInterval like this:

const interval = setInterval(() => {
  const el = document.getElementById('myElement')
  if (window.getComputedStyle(el).getPropertyValue("opacity") === 0) {
    clearInterval(interval)
    // execute your animate complete code here
  }
}, 100)

This interval will cease to fire as soon as the animation completes.

However, if you are willing to use jQuery that does have an animation complete callback function. The function will be executed when the animation is complete.

Docs are here: http://api.jquery.com/animate/

Here is an example of what the jQuery code might look like:

$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    console.log('Animation complete.')
  });
});
Related