I am looking for a way to dynamically populate a submenu depending on the selection of the main menu, then, when a user clicks on an item in the submenu, it populates two flexboxes with the contents of another file. I can’t figure out how to target a flexbox using JS; or, if that’s not possible, what I could do instead. For example:
JavaScript
x
4
1
MENU 1 MENU 2 MENU 3 // user selects menu 2, which populates the submenu from a file
2
^
3
submenu 1 submenu 2 submenu 3 // user selects submenu 3, which populates the flexbox containers
4
FLEXBOX CONTAINERS:
JavaScript
1
10
10
1
------------------------ -----------------------------------------
2
| SUBMENU 3 HTML PAGE | | SUBMENU 3 HTML PAGE |
3
| | | |
4
| | | |
5
| has options that | | dynamically populates |
6
| affect the contents | | based on the options selected |
7
| of the other box | | in the other box |
8
| | | |
9
------------------------ -----------------------------------------
10
Is this possible? What should I search to figure it out? I have Googled to no avail, I’m not searching for the right phrase. What should I be looking for?
Advertisement
Answer
Here is one possible implementation. You add an event listener on each trigger element—in my case, a button
. When the button is clicked, you target the .flex
element adjacent to the button and dynamically insert HTML
content.
JavaScript
1
18
18
1
const btns = Array.from(document.querySelectorAll('button'))
2
3
const clearContent = () => {
4
Array.from(document.querySelectorAll('.flex')).forEach(item => item.innerHTML = '')
5
}
6
7
btns.forEach((btn, index) => {
8
btn.addEventListener("click", () => {
9
clearContent();
10
btn.parentNode.querySelector('.flex').innerHTML = menuContents[index]
11
})
12
})
13
14
const menuContents = [
15
'<div>sub 1</div><div>sub 2</div><div>sub 3</div>',
16
'<div>sub 4</div><div>sub 5</div><div>sub 6</div>',
17
'<div>sub 7</div><div>sub 8</div><div>sub 9</div>'
18
]
JavaScript
1
24
24
1
.flex {
2
text-align: center;
3
display: flex;
4
position: absolute;
5
left: 50%;
6
top: 1.5rem;
7
transform: translateX(-50%);
8
column-gap: 1rem;
9
white-space: nowrap;
10
}
11
12
.flex:empty {
13
display: none;
14
}
15
16
.outer {
17
position: relative;
18
}
19
20
body {
21
display: flex;
22
justify-content: center;
23
gap: 1rem;
24
}
JavaScript
1
20
20
1
<div class="outer">
2
<button>
3
Menu 1
4
</button>
5
<div class="flex"></div>
6
</div>
7
8
<div class="outer">
9
<button>
10
Menu 2
11
</button>
12
<div class="flex"></div>
13
</div>
14
15
<div class="outer">
16
<button>
17
Menu 3
18
</button>
19
<div class="flex"></div>
20
</div>