Search code examples
eventsclickmootoolsdelayaddclass

MooTools – Add class to page on click of anchor, with delayed loading of anchor link


I'm using MooTools to add two classes to the body on click of a link from a nav menu, which triggers an animated CSS fade of the page.

I want to delay the link from loading the new page until the class has been added and a further 2s for the animation to take place.

My code is below. My attempt at this was to add a click event to the link, which adds the classes. I've used evt.stop to stop the new page loading, which allows the class to be added and the animation to subsequently trigger, but this stops the link from taking you to the new page altogether.

How can I adapt this code to do allow the link to work, but delayed as described above?

<nav id="main-nav">
  <ul>
    <li><a href="/page1.php">Page 1</a></li>
    <li><a href="/page2.php">Page 2</a></li>
  </ul>
</nav>    

$$('.page #main-nav li a').addEvent('click', function(evt) {
  evt.stop();
  $(document.body).addClass('animated fadeOut');
});

Solution

  • You could do something this way:

    $$('#main-nav li a').addEvent('click', function(evt) {
      evt.stop();
      // will break if clasList pr goes in if you do two in 1 string
      $(document.body).addClass('animated').addClass('fadeOut');
      // already extended.
    
      // should still use addEvent but declare animationend as a native one (type 2)
      // also, depends on browser, there needs to be detection for the right event name (prefix).
      document.body.addEventListener("animationend", function(){ 
        // at animation end, http://mootools.net/forge/p/cssevents for vendor shit
        window.location = evt.target.href; // simulate clicking on the a element
      }, false);
    
      // or at arbitrary time
      // setTimeout(function(){
      //  window.location = evt.target.href;
      // }, 2000);
    });