I've following code and I'm trying to get the transition to work, but could not. Seems something is wrong and I could not figure it out.
<div id="nav-links" class="fixed bg-bg-white overflow-scroll h-screen min-w-[80vw] left-[-100%] top-0 p-3 z-40 hidden transition-all duration-1000 ease-in">
</div>
<div class="flex flex-col gap-1 cursor-pointer" onclick="navOpen()">
<div class="w-7 h-1 bg-black rounded-md"></div>
<div class="w-8 h-1 bg-black dounded-md"></div>
<div class="w-6 h-1 bg-black rounded-md"></div>
</div>
Below is the JS.
function navOpen() {
const Overlay = document.getElementById('overlay');
const NavLinks = document.getElementById('nav-links');
document.body.classList.add('h-screen', 'overflow-hidden');
Overlay.classList.remove('hidden');
NavLinks.classList.remove('hidden', 'left-[100%]');
NavLinks.classList.add('left-0');
}
CSS transitions cannot happen on the same frame the display
is changed from none
. You can wait a frame using requestAnimationFrame()
and adjusting the left
property for the new frame:
function navOpen() {
// const Overlay = document.getElementById('overlay');
const NavLinks = document.getElementById('nav-links');
document.body.classList.add('h-screen', 'overflow-hidden');
// Overlay.classList.remove('hidden');
NavLinks.classList.remove('hidden');
requestAnimationFrame(() => {
NavLinks.classList.remove('left-[-100%]');
NavLinks.classList.add('left-0');
});
}
<script src="https://cdn.tailwindcss.com/3.4.3"></script>
<div id="nav-links" class="fixed bg-bg-white overflow-scroll h-screen min-w-[80vw] left-[-100%] top-0 p-3 z-40 hidden transition-all duration-1000 ease-in">
</div>
<div class="flex flex-col gap-1 cursor-pointer" onclick="navOpen()">
<div class="w-7 h-1 bg-black rounded-md"></div>
<div class="w-8 h-1 bg-black dounded-md"></div>
<div class="w-6 h-1 bg-black rounded-md"></div>
</div>
You may also wish to consider transitioning with transform: translateX()
since it is more performant:
function navOpen() {
// const Overlay = document.getElementById('overlay');
const NavLinks = document.getElementById('nav-links');
document.body.classList.add('h-screen', 'overflow-hidden');
// Overlay.classList.remove('hidden');
NavLinks.classList.remove('hidden');
requestAnimationFrame(() => {
NavLinks.classList.remove('-translate-x-full');
});
}
<script src="https://cdn.tailwindcss.com/3.4.3"></script>
<div id="nav-links" class="fixed bg-bg-white overflow-scroll h-screen min-w-[80vw] -translate-x-full top-0 p-3 z-40 hidden transition duration-1000 ease-in">
</div>
<div class="flex flex-col gap-1 cursor-pointer" onclick="navOpen()">
<div class="w-7 h-1 bg-black rounded-md"></div>
<div class="w-8 h-1 bg-black dounded-md"></div>
<div class="w-6 h-1 bg-black rounded-md"></div>
</div>