I am a novice programmer so I apologise if this does not make sense. I am developing a website and I am trying to implement a hamburger menu and a close button to exit the hamburger menu. The javascript function is working fine on one page's class attribute but not on the other page's same class attribute.
Here is my code
var close_popup = document.querySelector('.cancel-icon');
close_popup.addEventListener('click', function(){
document.getElementById('toggle').checked = false;
});
Here is my HTML code
<label class="Hamburger" for="toggle">☰</label>
<input type="checkbox" id="toggle"/>
<!-- Navigation Bar -->
<nav class="navbar">
<div class="cancel-icon" ><span>X</span></div>
<a class="navlink1" href="Profile.html">Profile</a>
<a class="navlink2" href="Portfolio.html">Portfolio</a>
<a class="navlink3" href="Contact.html">Contact</a>
</nav>
</div>
Here is the CSS
#toggle:checked + .navbar{
top: -12vh;
visibility: visible;
min-height: 100vh;
background-color: #3A3B3C;
transform: scale(1.5);
transition: all 0.5s ease-in-out;
}
this code is making sure if the checkbox for the hamburger menu is checked then make it false. So far it works on one page but not on the others. What am I doing wrong. Thanks
Your javascript is working properly. Clicking the ".cancel-icon" does close the opened menu. The main problem is that the ".cancel-icon" element is hidden when the menu is open which prevents you from being able to click the "X" icon.
Here is an updated example where I have rearranged the HTML and added some additional CSS rules in order to keep the "X" icon visible when the menu is open. The CSS positioning can be adjusted as needed.
var close_popup = document.querySelector('.cancel-icon');
close_popup.addEventListener('click', function() {
document.getElementById('toggle').checked = false;
});
#toggle:checked+.navbar {
top: -12vh;
visibility: visible;
min-height: 100vh;
background-color: #3A3B3C;
transform: scale(1.5);
transition: all 0.5s ease-in-out;
}
.cancel-icon {
z-index: 10;
position: absolute;
right: 65px;
top: 5px;
}
.cancel-icon:hover {
cursor: pointer;
}
<label class="Hamburger" for="toggle">☰</label>
<input type="checkbox" id="toggle" />
<!-- Navigation Bar -->
<nav class="navbar">
<a class="navlink1" href="Profile.html">Profile</a>
<a class="navlink2" href="Portfolio.html">Portfolio</a>
<a class="navlink3" href="Contact.html">Contact</a>
</nav>
<div class="cancel-icon"><span>X</span></div>