I am aiming to accomplish the following - when a dropdown-item from the navbar is selected, I want to execute BOTH of the following actions:
- Scroll to the div with the specified target id
- Collapse the navbar back to its initial state (fully rolled up, hidden)
So far, I have only been able to achieve one of the above actions at a time. Can anyone offer guidance on how I can accomplish both tasks simultaneously? I believe the first dropdown-item anchor should handle this, but for some reason, it fails to scroll to the targetId after collapsing the navbar. When I remove data-toggle="collapse"
and
data-target=".navbar-collapse.show"
as shown in the second anchor, the anchor successfully scrolls to the target but the navbar does not collapse.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<nav class="navbar navbar-dark bg-dark fixed-top">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Menu</a>
<div class="dropdown-menu shadow rounded" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#targetId" data-toggle="collapse" data-target=".navbar-collapse.show">The nav-link hides, but doesn't scroll to the target</a>
<a class="dropdown-item" href="#targetId">Scrolls to the target, but the nav-link doesn't hide</a>
</div>
</li>
</ul>
</div>
</nav>
<!-- navbar ends here -->
<div id="targetId">Content</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2928d92928790cc8891a2d3ccd3d4ccd2">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
Thank you for your assistance!