Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unfocus the modal trigger button after closing the modal in bootstrap

I can't seem to blur the button after closing the modal.

$('#exampleModal').on('hidden.bs.modal', function(e){
        $('button').blur();
    });

I've tried the above and it still doesn't seem to blur it. I've tried almost everything. The only solution is to set a timeout and blur it after the model finishes the hidden transition. Any better solution?

like image 728
holyxiaoxin Avatar asked Feb 20 '15 14:02

holyxiaoxin


People also ask

How do I keep my bootstrap modal from closing when I click the button?

To prevent closing bootstrap modal when click outside of modal window we need add properties data-backdrop="static" and data-keyboard="false" to button which we are using to show modal window like as shown following.

How do I close trigger modal?

There are few ways to close modal in Bootstrap: click on a backdrop, close icon, or close button. You can also use JavaScript hide method. Click the button to launch the modal. Then click on the backdrop, close icon or close button to close the modal.

How do I hide the modal when I click outside?

modal -> #modal-root -> body while clicking outside the modal will only go through #modal-root -> body . Since we can stop the propagation of click events completely, and if that does not interfere with any other code, we only need to listen for click events in both .


1 Answers

The focus back to the trigger element is set within the modal plugin using a .one() binding, which unfortunately cannot be unbound. The good news is we can do this:

$('#myModal').on('shown.bs.modal', function(e){
    $('#myModaltrigger').one('focus', function(e){$(this).blur();});
});

Where #myModaltrigger is the ID of the modal trigger button. The reason to use the .one() binding is so that the function to blur will be called only after the modal is shown. Once it hides, and the focus/blur happens, the button can be focused normally, like by tabbing to it, without it automatically blurring.

See this working example

like image 55
Ted Avatar answered Jan 28 '23 09:01

Ted