Hi everybody!
I was looking at the implementation in:
I would like to add some divs in the html, that are initially hidden. Once the user clicks on menu item/subitem the respective div appears based on an id. Any suggestions?
It’s probably best to do it with some JS to toggle the display of the element.
Add a class of .destination to the menu items as required and supply the destination ID in the href.
e.g.
<li class="menu-item"><a class="destination" href="#section1">Big Widgets</a></li>
<li class="menu-item"><a class="destination" href="#section2">Bigger Widgets</a></li>
... and so on....
Then the html would be something like.
<main class="main">
<section id="section1" class="section s1">
<h2>Section 1 big Widgets</h2>
</section>
<section id="section2" class="section s2">
<h2>Section 2 Bigger Widgets</h2>
</section>
etc...
</main>
Then call it with some JS.
(function (d) {
"use strict";
const menu = d.querySelectorAll(".destination");
const section = d.querySelectorAll(".section");
//hide all by default
section.forEach((item) => {
item.classList.add("hide");
});
menu.forEach((item) => {
item.addEventListener("click", (event) => {
hideAll();
showDiv(item.hash);
});
});
function hideAll() {
section.forEach((item) => {
item.classList.add("hide");
item.classList.remove("active");
});
}
function showDiv(targetDiv) {
d.querySelector(targetDiv).classList.add("active");
}
})(document);
Lastly some CSS to style it.
.menu{
height:60px;/* this will be needed otherwise the page will jump with the expanding menu */
}
.main{
max-width:1080px;
margin:auto;
}
.section{
padding:1rem;
background:#ccc;
}
.section.hide{display:none;}
.section.active{
display:block;
}
That’s the basics anyway.
Here’s a codepen that demonstrates the above although it has a couple of extra functions to highlight the nav and to turn off the current one.