Lewis A
Lewis A

Reputation: 3

CSS page transition by adding & removing a class (Vanilla JavaScript)

I'm attempting to create a transition that quickly fades in the page on load and then when a link is clicked, the page fades out and moves up slightly.

To do this I created the class 'is-loaded' which I would apply to the elements ('wrapper' and 'page-fade'). When the document is loaded, the 'is-loaded' class would be added, then when a link is clicked, the same class would be removed from both elements.

The code:

.wrapper {
transform: translateY(-25px);
transition: transform cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.3s; 
}

.wrapper.is-loaded {
transform: translateY(0); 
}

.page-loader {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #ffffff;
z-index: 999999;
transition: opacity cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.4s, visibility cubic-bezier(0.25, 0.46, 0.45, 0.95) 0.4s; 
}

.page-loader.is-loaded {
opacity: 0;
visibility: hidden; 
}
document.querySelectorAll('a').forEach(e => {
  e.addEventListener('click', function() {

    event.preventDefault()

    var i = this.getAttribute('href')
    var wrapper = document.querySelector('wrapper');
    var pageloader = document.querySelector('page-loader');

        wrapper.classList.remove('is-loaded'),
      setTimeout(function() {
        pageloader.classList.remove('is-loaded');
      }, 80),
      setTimeout(function() {
        window.location = i
      }, 100)
  })
})

document.addEventListener("DOMContentLoaded", function() {
  var wrapper = document.querySelectorAll('wrapper');
  var pageloader = document.querySelectorAll('page-loader');

  wrapper.classList.add('is-loaded'),
  pageloader.classList.add('is-loaded');
})

I'm new to writing in JavaScript so i'm unsure why my code does nothing. Is there a way to get this to work? No jQuery please and just vanilla js. Thank you.

Upvotes: 0

Views: 145

Answers (1)

Ito Pizarro
Ito Pizarro

Reputation: 1607

You're missing the prefix selector notation . necessary to find 'wrapper' or 'page-loader' with document.querySelector()|document.querySelectorAll(). In both cases, you'd use the same kind of selector syntax as you do in your CSS.

var wrapper = document.querySelectorAll('.wrapper'); 
var pageloader = document.querySelectorAll('.page-loader');

Also, document.querySelectorAll() returns a(n Array-like) HTML NodeList, which doesn't have a classList property. You could convert the NodeList to an Array and iterate through the result, adding to the classList of each element or, if you know there's only one of what you're looking for on the page, swap document.querySelectorAll() for document.querySelector() — which will return a single element.

Upvotes: 1

Related Questions