Search code examples
javascriptcsstransitiononbeforeunload

Page transition


I'm trying to apply a page transition. It basically consists in adding a class to a div and run the transition before page unload. This is what I have.
https://codepen.io/bcrvlh/pen/mddOQLx

window.addEventListener("beforeunload", function(event) { 
$("a").click(function(){
$("bottom-layer").addClass("active");});
});

can you give me a help? thanks


Solution

  • HTML

    <a href="#">click</a>
    <div id="bottom-layer" class="bottom-layer"></div>
    

    JS

    window.onload = function(){
      let element = document.getElementById("bottom-layer");
      element.classList.add("active");
    };
    

    With jQuery

    $(document).ready(function(){
      $('#bottom-layer').addClass('active');
    })
    

    If you want it to happen before page unloads you should create a function for each click and set a timeout for example:

    Html

    <a onclick = "navigate('place-href-here')"></a>
    

    JS

    function navigate(href-received-as-argument){
      let element = document.getElementById("bottom-layer");
      element.classList.add("active");
      setTimeout(function() {
       window.location.href = href-received-as-argument;
      }, 1000);
    }