I need some help regarding this javascript code that I have implemented on my website. Basically when clicking the hamburger on the fixed header, the fullscreen mobile menu is shown but before it completely appears I have set an animation which lasts for .25 seconds.
By clicking on the hamburger I am triggering the class header-proper-state
to set the header position to relative
in order to be able to see and use the hamburger on fixed
position when the menu is shown. Everything works except the thing that for those .25 seconds the header is missing and creates an unpleasant visual effect before the fullscreen menu is completely shown. As workaround I have set a 300ms delay for the toggle
and I have no visual issues before the menu is completely shown but when I click again on the hamburger close button, I have to wait 300ms more to see the header on fixed position. So I have tried to change toogle
to add
and also to set a different delay (like 40) for a new function when clicking on the close button is-active
and used remove
to remove the class that positions the header on relative
while the meby us shown, in order to have the correcte delays but I am getting errors from console and no class is removed, basically it says that close
is null. What am I missing?
This is my code:
document.addEventListener("DOMContentLoaded", function(event) {
let hamb = document.querySelector('.hamburger')
let bdy = document.querySelector('body')
let close = document.querySelector('.is-active')
hamb.addEventListener('click', function(e) {
this.classList.toggle('is-active');
setTimeout(function() {
document.querySelector('.mobile-menu').classList.toggle('mob-menu-show')
}, 50);
setTimeout(function() {
document.querySelector('.mob-menu-base').classList.toggle('mob-menu-base-anim')
}, 50);
setTimeout(function() {
document.querySelector('.mobile-menu-content').classList.toggle('mobile-menu-animations')
}, 100);
setTimeout(function() {
document.querySelector('.header-wrapper').classList.add('header-proper-state')
}, 300);
bdy.classList.toggle('prevent-scroll');
});
close.addEventListener('click', function(e) {
setTimeout(function() {
document.querySelector('.header-wrapper').classList.remove('header-proper-state')
}, 40);
});
});
The variable close
is set at the start of the code. It will at that time be null
as there are no elements with the is-active class
.
It appears that it is never changed so when you come to do the addEventListener
on it you get the error.
The variable close
needs updating each time before it is used to make sure it refers to the current element that has class="is-active"
.