data-keyboard="false" doesn't work in bootstrap for the following code

489 Views Asked by At

I dont want the esc key to toggle my dropdown. so I added the data-keyboard="false". But that doesn't seem to work and my code still toggles on esc key.

code: https://jsfiddle.net/4dkfj63v/21/

<div class="dropdown">
    <button class="btn dropdown-toggle" 
            type="button" 
            id="dropdownMenu1" 
            data-toggle="dropdown" 
            aria-haspopup="true" 
            data-keyboard="false"
            aria-expanded="true">
       Options 
       <span class="caret"></span> 
    </button>
    <ul class="dropdown-menu" id="myDrop" aria-labelledby="dropdownMenu1" data-keyboard="false" >
      <li>
        Option 1
      </li>
      <li>
        Option 2
      </li>
      <li>
        Option 3
      </li>

    </ul>
</div>
2

There are 2 best solutions below

3
tao On BEST ANSWER

This should do it:

$('.dropdown').on('keydown', '.dropdown-toggle', ({ key }) => key !== 'Escape')

See it working.


Note: you tagged your question bootstrap-4 and bootstrap-5 but in your fiddle you're using Bootstrap 3. Which version are you actually using? The above method works on both v3.* and v4.*, as long as you're loading jQuery.
Haven't tested it on v5.*

4
A. Meshu On

For bootstrap5:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>



<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        TRY CLICK ON ESC
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>

Seems that you need to set this attribute to the modal itself as mentioned here (not to the button as you did).

And it's not data-keyboard="false" BUT data-bs-keyboard="false".

Check the link i provided - its from bootstrap docs.