Utilizing a Bootstrap offcanvas for a <nav>
menu on a mobile site, I aim to navigate users to specific sections of the website when they click on a <li>
. I've implemented a simple JavaScript script that triggers the offcanvas exit button and then uses an ID to scroll the user to the designated section. However, an issue arises where the offcanvas scrolls the website back to its original position.
The functionality works as intended until the button regains focus or another event triggers a scroll back to the top where the button is located.
Upon investigation, I've discovered that Bootstrap adds an 'open-modal' class to the body when using modals, and I assume a similar class is added when using offcanvas, which may interfere with scrolling. I've also learned that removing the
data-bs-toggle="offcanvas"
attribute can help when creating elements dynamically with JavaScript, but that is not the case here. How can I resolve this issue and achieve the desired effect on the site? Below is the JavaScript file and the HTML for the <nav>
.
JAVASCRIPT:
function ServicePackages(){
const exitBtn = document.getElementById('button-close');
exitBtn.click();
window.location.href = "#service-packages";
}
// Repeat similar functions for other sections...
function Home(){
const exitBtn = document.getElementById('button-close');
exitBtn.click();
window.location.href = "#home";
}
HTML:
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="javascript: return false">
<img class="d-inline-block align-text-bottom" src="assets/logo.png" width="156px" height="45px">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#navModal"
aria-controls="offcanvasRight">
<span class="navbar-toggler-icon"></span>
</button>
<div class="offcanvas offcanvas-end" tabindex="-1" id="navModal" aria-labelby="offcanvasRightLabel">
<div class="offcanvas-header">
<img class="offcanvas-title d-inline-block align-text-bottom" src="assets/logo.png" width="156px"
height="45px">
<button id="button-close" class="btn-close" type="button" data-bs-dismiss="offcanvas"
aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<script src="modal.js"></script>
<ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
<li class="nav-item">
<a class="nav-link" onclick="ServicePackages()" aria-current="page"
href="#service-packages">SERVICE
PACKAGES</a>
</li>
<li class="nav-item">
<a class="nav-link" onclick="IndividualServices()" aria-current="page"
href="#individual-services">INDIVIDUAL
SERVICES</a>
</li>
// Repeat similar <li> elements for other sections...
<li class="nav-item">
<a class="nav-link active" onclick="Home()" aria-current="page" href="#home">HOME</a>
</li>
</ul>
</div>
</div>
</div>
</nav>