Search code examples
javascripthtmlangulartypescriptanimate.css

Animate.css add animation on click


I want to animate an image input when the user click the image, I'm using animate.css with Bootstrap and Angular, I've seen some examples to add the animate class when the image is click but nothing happens, when I console.log the element in the function I can see that the animate class is added but didnt work, also I got an error message in the console.

html code

<input type="image" src="../../../assets/img/as-logo-150dpi-05.png" class="d-block animate__animated animate__slideInLeft" id="offMenu" (click)="animateLogo()">

TS code

animateLogo(){
    const element = document.querySelector('#offMenu');
    if(element) {
      element.classList.add('animate__animated', 'animate__bounceOutRight');
      console.log(element)
    }
  }

As you can see in the input class, the aniimate class "animate__bounceOutRight" is added but nothing happens in my project, any advice on this?

So after the answer I found out the error message is because of bootstrap, nothing to do with the animation, and the problem was because the input already have an animation, when the function added another this overlaps and didint make it work so I need to disable the first one to make the second works but now the input disappear because of the second animation

HTML

<input type="image" src="../../../assets/img/as-logo-150dpi-05.png" class="d-block animate__animated animate__slideInLeft" id="offMenu" [ngClass]="{'animate__slideInLeft ': firstAnimation , 'animate__bounceOutRight': secondAnimation }" (click)="animateLogo()">

TS

firstAnimation: boolean; //This is true
 secondAnimation: boolean; //This is false
    
 animateLogo(){
    this.firstAnimation = false
    this.secondAnimation = true
  }

Solution

  • Did you add the animate.css styles in your

    angular.json

    "styles": [
        "node_modules/animate.css/animate.css"
      ],
    

    OR

    styles.css:

    @import '~animate.css/animate.min'

    Also just for a better approach let's try to do tackle your problem the Angular way

    In your .ts create a boolean field named activateAnimation and we'll set it as true when the user clicks the image so your .ts code will look something like this:

      activateAnimation: boolean;
        
      animateLogo(): void {
         this.activateAnimation = true
      } 
    

    and then in your HTML we can conditionally add the animate.css classes that you want to add using the [ngClass] directive of Angular.

    <input type="image" src="../../../assets/img/as-logo-150dpi-05.png"
        class="d-block animate__animated animate__slideInLeft"
        [ngClass]="{'animate__animated ': activateAnimation , 'animate__bounceOutRight': activateAnimation }" id="offMenu"
        (click)="animateLogo()">```