Search code examples
javascriptjquerybootstrap-4bootstrap-modalsetfocus

Bootstrap modal set focus on popup close to input in body


Hi Stack overflow community people

I wanted to set the focus on input when users click on the bootstrap modal window.

I tried the below code but not helping. Any help appreciated.

$('#myModal').on('hidden.bs.modal', function() {
  $('#focusMe').focus()
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">

<!--CB-modal -->
<!-- Button trigger modal -->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<label>Foucs Me</label>
<input type="text" id="focusMe">

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
<!-- JS code -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js">
</script>


Solution

  • You just need to add setTimeout() function before calling focus() event for input.

    In your code focus() method called right after bootstrap modal get closed, when DOM is not loaded properly.

    $('#myModal').on('hidden.bs.modal', function() {
      setTimeout(function(){
          $('#focusMe').focus();
      },100);
    });