Reputation: 947
I'm building a simple flexbox navigation, when the screen size is below 980px a mobile version of the menu shows.
I'm building the javascript to do this - does anyone know why my console.log message won't show when the mobile version of the menu is clicked?
It's driving me around the twist.
You have to reduce the window below 980px to see what i mean.
https://codepen.io/emilychews/pen/eezYox?editors=1111
var mobileMenuButton = document.querySelector('#mobile-menu')
var mobileMenuItems = document.querySelector('#nav-menu')
// TOGGLE MOBILE MENU
var mobileMenu = false
if (mobileMenu === false) {
function showMobileMenu() {
mobileMenuButton.onclick(function() {
console.log("clicked");
})
mobileMenu = true
}
}
* {
padding: 0;
margin: 0;
}
p {
color: white;
}
header {
width: 100%;
}
#main-nav {
width: inherit;
height: 100px;
background: red;
display: flex;
justify-content: space-between;
box-sizing: border-box;
padding: 10px 5% 10px 5%;
align-items: center;
}
#logo-wrapper {
width: 150px;
height: 75px;
background-color: grey;
}
#nav-menu {
display: flex;
margin-left: auto;
}
#main-nav ul li {
list-style-type: none;
padding: 5px 10px;
background: pink;
margin: 0 5px;
}
#mobile-menu {
display: none;
}
@media only screen and (max-width: 980px) {
#mobile-menu {
display: block;
background: blue;
padding: 5px 10px;
box-sizing: border-box;
cursor: pointer;
z-index: 99;
}
#main-nav ul {
display: none;
}
}
<header>
<nav id="main-nav">
<div id="logo-wrapper"></div>
<ul id="nav-menu">
<li class="menu-item menu-item-1"><a>Home</a></li>
<li class="menu-item menu-item-2"><a>About</a></li>
<li class="menu-item menu-item-3"><a>Contact</a></li>
</ul>
<div id="mobile-menu"><a>Menu</a></div>
</nav>
</header>
Upvotes: 0
Views: 115
Reputation: 5577
Well there are few problems, You never call showMobileMenu
function, so event is never binded to that element. onclick
is not a function. I believe You want something like:
var mobileMenuButton = document.querySelector('#mobile-menu')
var mobileMenuItems = document.querySelector('#nav-menu')
// TOGGLE MOBILE MENU
var mobileMenu = false
mobileMenuButton.addEventListener('click', function() {
toggleMobileMenu();
})
function toggleMobileMenu() {
if (mobileMenu === false) {
console.log("clicked");
mobileMenu = true
} else {
console.log("not clicked");
mobileMenu = false
}
}
Upvotes: 1