Create an offcanvas sidebar which opens from the left

Description: A “Menu” button must open a sidebar from the left side, with two links and a close button.

Hint:

  • Use offcanvas offcanvas-start, data-bs-toggle="offcanvas" and data-bs-dismiss="offcanvas".

Solution

<button class="btn btn-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebar" aria-controls="sidebar">Menu</button>
<div class="offcanvas offcanvas-start" tabindex="-1" id="sidebar" aria-labelledby="sidebarLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="sidebarLabel">Menu</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <a class="d-block mb-2" href="#">Home</a>
    <a class="d-block" href="#">Contact</a>
  </div>
</div>
Live preview

const s = document.getElementById('sidebar');
document.querySelector('[data-bs-toggle="offcanvas"]').click();
await new Promise(r => setTimeout(r, 700));
console.log('open: ' + s.classList.contains('show'));
s.querySelector('.btn-close').click();
await new Promise(r => setTimeout(r, 700));
console.log('open after close: ' + s.classList.contains('show'));
Console output (real Chrome)

open: true
open after close: false

How it works

  • offcanvas-start places the panel on the left side. The toggle button opens it, and the close button closes it.

Read Offcanvas.


Learn more about the similar topics:
Tutorials
Bootstrap Modal
Bootstrap Collapse and Accordion
Bootstrap Carousel
Bootstrap Tooltips and Popovers
Bootstrap Offcanvas
Bootstrap Toasts
Bootstrap JavaScript: Data Attributes, API and Events
Exercises & Assignments
Open a modal with a button
Create an accordion with three items
Create a carousel with three slides
Add a tooltip to a button
Create an offcanvas sidebar which opens from the left
Interview Questions & Answers
How do you open a modal in Bootstrap?
How do you create a carousel in Bootstrap?
What are data-bs-* attributes in Bootstrap?
How do you initialize tooltips and popovers in Bootstrap 5?
What is the offcanvas component in Bootstrap?
What is Popper and why does Bootstrap need it?
How do you use the Bootstrap JavaScript API?