Code Tricks

Play Lottie on hover

Play the lottie when hovering on the card.

Created by

Code & Wander

See resource

Code

<!-- Code by Code & Wander https://www.codeandwander.com/ -->
<script>
  // Wait for the DOM to be fully loaded
  document.addEventListener('DOMContentLoaded', function () {    
    // Select all the .card elements    
    const cards = document.querySelectorAll('.card');    
    // Add event listeners to each card    
    cards.forEach(function(card) {        
      card.addEventListener('mouseenter', function() {            
        // Find the dotlottie-player element within the current card            
        const lottiePlayer = card.querySelector('dotlottie-player');            
        // Play the Lottie animation            
        lottiePlayer.play();        
      });        
      card.addEventListener('mouseleave', function() {            
        // Find the dotlottie-player element within the current card            
        const lottiePlayer = card.querySelector('dotlottie-player');            
        // Stop the Lottie animation            
        lottiePlayer.stop();        
      });    
    });
  });
</script>

Copied!

Tutorial

Steps & Description

The above code takes into account adding the lottie as a custom element.

Change the .card class to the class you would like to target.

Change "dotlottie-player" to the HTML tag used.

Tips & Notes

"dotlottie-player" will be used for .lottie files. If you are using .json then you will have to use the "lottie-player" tag.