Search code examples
twitter-bootstrapmodal-dialogtooltip

How can I prevent the focus on the toggle button for a Bootstrap modal after the modal closes?


I have a button that toggles a Bootstrap modal. The button itself is wrapped in a div so a tooltip shows up on hover.

When I close the modal, the button gets focused and the tooltip shows without hovering the element.

<span data-toggle="tooltip" data-placement="top" data-title="Tooltip">
    <button  data-toggle="modal" data-target="#modal">Toggle</button>
</span>

 <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
     <div class="modal-dialog">
         <div class="modal-content">
             <div class="modal-header">
                 <button type="button" class="close" data-dismiss="modal">&times;</button>
             </div>
             
             <div class="modal-body">
                 <p>lorem ispum dolor sit amet</p>
             </div>
             
             
             <div class="modal-footer">
                 <button type="button" class="btn btn-primary">Submit</button>
                 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
             </div>
         </div>
     </div>
</div>

See here exactly what's happening: http://jsfiddle.net/6t3kxhLb/

The only workaround I could come up with up until now was to blur the button when the hidden.bs.modal event fires up. But I'm not really happy with the result.

This is my workaround:

$('#modal').on('hidden.bs.modal', function(event){
    setTimeout(function(){
      $('[data-toggle="modal"]').blur();
    });
 });

Do you guys know any way to prevent the focus on the toggle button when the modal closes?


Solution

  • As per the Bootstrap documentation, you need to specify what triggers the tooltip. The options are click, hover, focus and manual while the default is to have both hover and focus. so just add data-trigger="hover" to your element:

    <span data-toggle="tooltip" data-placement="top" data-title="Tooltip" data-trigger="hover">
        <button  data-toggle="modal" data-target="#modal">Toggle</button>
    </span>
    

    Example fiddle: http://jsfiddle.net/6t3kxhLb/1/