Reputation: 2270
What am I trying to do. I have a menu navigation with 2 menu items the search and hamburger icon next to each other.
When I click on "MENU" the div will display the menu navigation items and will close when I click once again because of the toggle event.
However, when I open up "MENU" and switch back to "SEARCH" where, a different div should be displayed it messes up the logical structure between these two on toggle.
So, I want to toggle between SEARCH and MENU content no matter which one is selected / toggled. To close previous (remove class and add class to the next active element).
How can I do this?
HTML:
<a href="#" class="search js-search">SEARCH</a>
<a href="#" class="hamburger js-hamburger">MENU</a>
<nav class="navigation js-navigation">
<div class="content hidden">
<input type="search" placeholder="search" />
</div>
<div class="content hidden">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
JS:
(() => {
const navigation = document.querySelector('.js-navigation');
if(!navigation) {
return;
}
const hamburger = document.querySelector('.js-hamburger');
const search = document.querySelector('.js-search');
let contents = document.querySelectorAll('.content');
const onClick = (e) => {
e.preventDefault();
contents.forEach((content) => {
content.classList.remove('hidden');
content.classList.add('hidden');
})
}
hamburger.addEventListener('click', onClick);
search.addEventListener('click', onClick);
});
Upvotes: 1
Views: 967
Reputation: 167
Shouldnt you add:
if (content.classList.contains("hidden")) {
content.classList.remove('hidden');
} else {
content.classList.add('hidden');
}
Changeing classList didnt work for me, but this took effect:
<html>
<body>
<a href="#" class="search js-search" onClick="toggle('search');">SEARCH</a>
<a href="#" class="hamburger js-hamburger" onClick="toggle('menu');">MENU</a>
<nav class="navigation js-navigation">
<div id="search" class="content">
<input type="search" placeholder="search" />
</div>
<div id="menu" class="content">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
<script>
function toggle(id) {
var isHidden = document.getElementById(id).style.visibility == "hidden";
document.getElementById(id).style.visibility = isHidden ? "visible" : "hidden";
}
</script>
</body>
</html>
Also seems you could alternatively go with classList.toggle:
const navigation = document.querySelector('.js-navigation');
const hamburger = document.querySelector('.js-hamburger');
const search = document.querySelector('.js-search');
let contents = document.querySelectorAll('.content');
const onClick = (e) => {
e.preventDefault();
contents.forEach((content) => {
content.classList.toggle('hidden');
})
}
hamburger.addEventListener('click', onClick);
search.addEventListener('click', onClick);
Upvotes: 1