Search code examples
javascripthtmlcssanimate.css

Delay anchor link destination till animation completes?


I am trying to make a page transition occurs with vanilla JS and CSS. I have a class that I wish to add to my element when the 'collection' button is clicked. I have a function where I delay the link redirection by using prevent default, adding a CSS animated class, and then setting a new window location after a delay of 4 seconds. However currently when I click on collections, nothing happens, although when I hover over the text, the link preview is correct. I'm using animate.css's built-in animation which just requires you to link its stylesheet in the head tag and add the animation class to the element.

HTML -

<div id="homeContainer" class="home-container">
         <div class="bg-home bg-move">
            <img src="/Home/Asset 3.png" alt="film">
         </div>
         <div class="nav-button-h text-fade">
            <p id="pressbtn">ABOUT</p>
            <p id="logo-center">SHEK LEUNG</p>
            <p id="aboutbtn">PRESS</p>
         </div>
         <div class="nav-button-v text-fade">
            <a href="/collections/MA/MA.html" class="text-fade" id="colbtn">COLLECTIONS</a>
            <p id="projbtn">PROJECTS</p>
         </div>
     </div>

JS

const colbtn = document.getElementById('colbtn');
const homeContainer = document.getElementById('homeContainer');

colbtn.addEventListener('click', animateDown);

function animateDown(e) {
   e.preventDefault();
   homeContainer.classList.add('animate__animated animate__fadeOutDown');
   if (this.href) {
      var target = this.href;
   }
   setTimeout(function () {
      window.location.replace(target);
   }, 4000);

}

Solution

  • You can't add classes like that, they need to be comma separated.

    const colbtn = document.getElementById('colbtn');
    const homeContainer = document.getElementById('homeContainer');
    
    colbtn.addEventListener('click', animateDown);
    
    function animateDown(e) {
      e.preventDefault();
      homeContainer.classList.add('animate__animated', 'animate__fadeOutDown');
      if (this.href) {
        var target = this.href;
      }
      setTimeout(function() {
        window.location.replace(target);
      }, 4000);
    
    }
    <div id="homeContainer" class="home-container">
      <div class="bg-home bg-move">
        <img src="/Home/Asset 3.png" alt="film">
      </div>
      <div class="nav-button-h text-fade">
        <p id="pressbtn">ABOUT</p>
        <p id="logo-center">SHEK LEUNG</p>
        <p id="aboutbtn">PRESS</p>
      </div>
      <div class="nav-button-v text-fade">
        <a href="/collections/MA/MA.html" class="text-fade" id="colbtn">COLLECTIONS</a>
        <p id="projbtn">PROJECTS</p>
      </div>
    </div>