Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Open modal / offcanvas with a single button click

I want to open my favorites sidebar with a single click on my keyboard. So when pressing "f" I want the sidebar modal to open. Now it opens like this:

<a href="#" data-bs-toggle="offcanvas" data-bs-target="#favorites">
    Open Favorites
</a>

I am unsure how to do this with jquery, I have been trying like this but without success:

$(document).keydown(function(e) {
 if (e.keyCode == "s") {
   $('#favorites').show();
 }
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To show/hide the offcanvas from the JavaScript you can use an offcanvas instance eg: const bsOffcanvas = new bootstrap.Offcanvas('#favorites');. Which has methods like hide, show, toggle. Also the keyCode for f is 70. So, when the key code is 70 you can show the offcanas with bsOffcanvas.show();. See the following example:

$(document).keydown(function(e) {
  console.log(e.keyCode);
  if (e.keyCode == 70) {
    const bsOffcanvas = new bootstrap.Offcanvas('#favorites');
    bsOffcanvas.show();
  }
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#"  type="button" data-bs-toggle="offcanvas" data-bs-target="#favorites">
    Open Favorites
</a>


<div class="offcanvas offcanvas-end" tabindex="-1" id="favorites" >
  <div class="offcanvas-header">
    <h5 id="offcanvasRightLabel">Favorites Offcanvas</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    ...
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading