How to keep scroll position in Bootstrap5 Offcanvas

When using Bootstrap5’s Offcanvas, there is a problem that scrolling the body with the Offcanvas open and then closing the Offcanvas returns the body to its original position (toggle button position). However, if the toggle button is fixed (fixed), this problem does not occur.

To solve this, use JavaScript to toggle the Offcanvas. Here is the code

var search_box = document.getElementById('search-box'); 
var search_box_canvas = new bootstrap.Offcanvas(search_box); 
$('.toggle-search').on ('click', function(e) { 
e.preventDefault(); 
e.stopPropagation(); 
search_box_canvas.toggle(); 

}

);

The above code first retrieves the Offcanvas element and creates a new Offcanvas instance. Then, when the toggle button is clicked, it toggles the Offcanvas, preventing the default event and propagation.

This way, the scroll position is retained even after the Offcanvas is closed.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top