Reputation: 188
My website uses Foundation 6.5.3 with responsive togggle navigation: Top-bar menu for desktop devices and the title-bar menu for devices with viewport below the large breakpoint.
I have many items in the navigation. This leads to it using two lines when viewport is below 1287 pixels. I don't want it to do that, instead, I'd like it to switch to the title bar menu at that point. The exact viewport where the problem occurs might change in the future when there are changes to the website's content. So what I want is that the menu switches from top bar to title bar as soon as it doesn't fit into one line anymore.
I have written this JavaScript code:
responsiveNav();
function responsiveNav() {
"use strict";
var topBar = document.querySelector(".top-bar");
var titleBar = document.querySelector(".title-bar");
if (topBar.offsetHeight > 48) {
topBar.style.display = "none";
titleBar.style.display = "flex";
} else {}
}
window.addEventListener('resize', responsiveNav);
It does work partially: When the top-bar is higher than 48 pixels, the title-bar is shown instead. But the menu is not interactive, when clicking the menu icon, nothing happens. What do I need to do to activate it?
Upvotes: 1
Views: 107
Reputation: 743
If I understood your problem, I think you are trying to add an event listener to an array of 2 buttons (1 for the top bar and 1 on the title bar), so it doesn't work. A possible solution can be the following one (open on new window and try to resize to see both modes working)
responsiveNav();
function responsiveNav() {
var topBar = document.querySelector(".top-bar");
var titleBar = document.querySelector(".title-bar");
if (window.innerWidth > 480) {
topBar.style.display = "none";
titleBar.style.display = "flex";
} else {
topBar.style.display = "flex";
titleBar.style.display = "none";
}
}
window.addEventListener('resize', responsiveNav);
var btn1 = document.querySelectorAll('.btn1');
btn1[0].addEventListener('click', event => {
console.log("btn1 clicked")
});
btn1[1].addEventListener('click', event => {
console.log("btn1 clicked")
});
.title-bar {
display: flex;
}
button {
width: 100px;
}
span {
width: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="title-bar">
This is my title
<span></span>
<button class="btn1">Button 1</button>
<button class="btn2">Button 2</button>
<button class="btn3">Button 3</button>
<button class="btn4">Button 4</button>
</div>
<div class="top-bar">
<button class="btn1">Button 1</button>
<button class="btn2">Button 2</button>
<button class="btn3">Button 3</button>
<button class="btn4">Button 4</button>
</div>
<script>
</script>
</body>
</html>
Notice that I added only the first button but you can easily add the others
Upvotes: 0