In my Blazor .Net 8 web application, I have implemented a Bootstrap 5.3 Offcanvas component as a menu for selecting items. I wanted the Offcanvas to close automatically when a user selects an item from the menu.
To achieve this functionality, I created a ButtonClicked
event that triggers the following JavaScript code:
`await JS.InvokeVoidAsync("closeOffcanvas");`
This is executed just before the OnFilterSelected EventCallback.
I used data-bs
attributes for incorporating Bootstrap. Despite extensive research, I could not find a solution. Below is the JavaScript code I developed in a file named closeOffcanvas.js
. Please note that my JavaScript skills are at a novice level.
The relevant code snippet can be found below. For a functional example, you can refer to this GitHub repository.
closeOffcanvas.js
window.closeOffcanvas = function () {
var offcanvasElement = document.getElementById("offcanvasid");
var offcanvas = new bootstrap.Offcanvas(offcanvasElement);
offcanvas.hide();
};
Filter.razor
<button class="btn btn-primary btn-sm" data-bs-toggle="offcanvas" data-bs-target="#offcanvasid">
Contents
<i class="fas fa-bars"></i>
</button>
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasid">
<div class="offcanvas-header">
<span></span>
<button type="button" class="btn-close"
data-bs-dismiss="offcanvas" aria-label="Close">
</button>
</div>
<div class="offcanvas-body">
<ul class="list-group">
@foreach (var item in Enums.MenuItem.List.OrderBy(o => o.Value))
{
<li class="list-group-item @ActiveFilter(item)">
<a @onclick="(e => ButtonClicked(item))"
type="button"
id="@item.ButtonId">
@item.Value <small>@item.Title</small>
</a>
</li>
}
</ul>
</div>
</div>
@code
[Parameter, EditorRequired] public required Enums.MenuItem? CurrentFilter { get; set; }
[Parameter] public EventCallback<Enums.MenuItem> OnFilterSelected { get; set; }
protected Enums.MenuItem currentMenuItem = Enums.MenuItem.HebrewPassOverOrCrossOver;
private async Task ButtonClicked(Enums.MenuItem filter)
{
currentMenuItem = filter;
// calling this doesn't close the component
// It also disables the close button
await JS.InvokeVoidAsync("closeOffcanvas");
await OnFilterSelected.InvokeAsync(filter);
}
// other code
Index.razor
This Razor page integrates the Filter.razor component.
@page "/"
<h1>Home</h1>
<div class="d-flex justify-content-end mx-1">
<Filter CurrentFilter=@CurrentFilter OnFilterSelected="@ReturnedFilter" />
</div>
<!-- Do something with the chosen filter -->
@code
public MenuItem CurrentFilter { get; set; } = MenuItem.HebrewPassOverOrCrossOver; // default item
private void ReturnedFilter(MenuItem filter)
{
CurrentFilter = filter;
StateHasChanged();
}