简体   繁体   中英

How do i get the navbar to close when i click on a <a> link?

So I am using a pure CSS nav bar that uses a checkbox to overlay a navigation menu. I am trying to get the navbar to close when I select the link. For instance, when I click the contact link it should scroll down to the id"contact" that is on the same page, however, the page scrolls down while the navbar is still showing and so I have to manually click the checkbox to close it. I have tried to solve this using some js but no luck :(

complete code link:

https://codepen.io/majorsyan/pen/Oqejox

<!-- Navigation code-->
<input type="checkbox" id="nav-toggle" class="checkbox" />
<label for="nav-toggle" class="nav-toggle-btn">
<span class="nav-icon-bar"></span>
</label>
<div class="overlay"></div>
<nav class="main-nav">
<ul class="nav-list">
<li class="nav-item">
<a href="index.html" class="nav-links">Home</a>
</li>
<li class="nav-item">
<a href="portfolio.html" class="nav-links">Portfolio</a>
</li>
<li class="nav-item">
<a href="about.html" class="nav-links">About</a>
</li>
<li class="nav-item">
<a href="index.html#contact" class="nav-links">Contact</a>
</li>
</ul>
</nav>

Setting the checked attribute on your checkbox should do the trick!

const links = document.querySelectorAll('.nav-item a')
const checkbox = document.querySelector('#nav-toggle')

for ( const link of links ) {
  link.onclick = handleClick
}

function handleClick() {
  checkbox.checked = false
}

Or, if you're using jQuery:

$('.nav-item a').click(hideOverlay)

function hideOverlay() {
  $('#nav-toggle').prop('checked', false)
}

Hope this helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM