cmp cmp - 10 days ago 4
CSS Question

Can I get a two-way transition speed with CSS for open and close?

I have a full-screen overlay menu.

.overlay {
height: 0%;
width: 100%;
position: fixed;
z-index: 70;
top: 0;
right: 0;
background-color:#415566;
overflow-y: hidden;
transition: 2.0s;
}

<div id="menuActive"><a href="javascript:void(0)" onclick="openNav()">&#9776;</a></div>

<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>


I have JS to call it to open and close:

function openNav() {
document.getElementById("navBar").style.height = "100%";
}

function closeNav() {
document.getElementById("navBar").style.height = "0%";
}


Is it possible to have a different transition time for
openNav()
and
closeNav()
? At present, I am only able to control both.

Answer

You could add an extra class to your .overlay to modify the transition:

 function openNav() {
    var navBar = document.getElementById("navBar");
    navBar.style.height = "100%";
    setTimeout(function(){
       navBar.classList.add("opened");
    }, 2000)
 }

 function closeNav() {
    var navBar = document.getElementById("navBar");
    navBar.style.height = "0%";
    setTimeout(function(){
       navBar.classList.remove("opened");
    }, 300)
 }

and the CSS for this class could be:

.opened {
    transition: height 300ms; /* The duration you want... */
}

Also, take the good advice given by skobaljic in the question's comments about using JS to just add/remove classes for this kind of interaction.

Comments