I am trying to create a foldable menu, through CSS and JS. Css works (almost) correctly (the menu folds and unfolds, even if the class is not correctly applied) but not the JS code, which should change the innerText of the <li> acting as a button from “>” to “<” and opposite.
I have been messing around with js code for a while (making sure that document.getElementById is not undefined), but neither element.innerText or element.innerHTML seem to work properly.
I have two questions:
-
When applying an animation, and having two classes, shouldn’t respect both classes (I mean, the navbar should be red)? Should I add nav class AFTER the animation is done, or fill the navbar in red color through the animation?
-
Why does ignore InnerText/InnerHTML instructions?? I have debugged the code and definitely goes through that instruction and I cannot understand why the change is not done…
var navButton;
var navbar;
const init = ()=>{
navbar = document.getElementById("navbar");
navButton = document.getElementById("foldButton");
navButton.addEventListener('click', function(){
if(navbar.className==="init nav" || navbar.className==="fade-out-right nav"){
navButton.InnerText=`<p><</p>`;
toggleFold();
}
else{
navButton.InnerText=`<p>></p>`;
toggleFold();
}
});
}
const toggleFold = () => {
if(navbar.className==="init nav" || navbar.className==="fade-out-right nav"){
navbar.className="fade-in-left nav";
}else{
navbar.className="fade-out-right nav";
}
};
* {
margin: 0;
padding: 0;
}
html {
box-sizing: border-box;
font-size: 62.5%;
scroll-behavior: smooth;
}
/* Base styles */
.nav {
display: flex;
justify-content: flex-end;
position: fixed;
top: 0;
left: 0;
width: 4%;
background: red;
box-shadow: 0 2px 0 rgba(0, 0, 0, 0.4);
z-index: 10;
}
.nav-list {
display: flex;
margin-right: 2rem;
list-style: none;
}
.nav-list li {
display: block;
font-size: 2.2rem;
padding: 2rem;
}
.nav-list a{
color:black
}
.nav-list a:hover {
background: blue;
}
.fade-in-left {
animation-name: fade-in-left;
animation-duration: 2s;
animation-timing-function: ease;
animation-fill-mode: forwards;
}
@keyframes fade-in-left {
from {
opacity: 1;
transform: translateX(-4%);
}
to {
opacity: 1;
transform: translateX(305px);
}
}
.fade-out-right {
animation-name: fade-out-right;
animation-duration: 2s;
animation-timing-function: ease;
animation-fill-mode: forwards;
}
@keyframes fade-out-right {
from {
opacity: 1;
transform: translateX(305px);
}
to {
opacity: 1;
transform: translateX(-4%);
}
}
<body onload="init()">
<nav id="navbar" class="init nav">
<ul class='nav-list'>
<li><a href='#welcome-section'>About</a></li>
<li><a href='#projects'>Work</a></li>
<li><a href='#contact'>Contact</a></li>
<li id="foldButton"><p>></p></li>
</ul>
</nav>
</body>
Thank you for helping me out.