I can\'t seem to blur the button after closing the modal.
$(\'#exampleModal\').on(\'hidden.bs.modal\', function(e){
$(\'button\').blur();
});
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
My solution which works with multiple modals on page (based on Bootstrap modal examples):
$('.modal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
button.one('focus', function (event) {
$(this).blur();
});
});
Indeed, @cvrebert is right here that doing this negatively impacts accessibility.
blur() resets the focus, so keyboard users (both sighted keyboard users, and more critically users of screenreaders) are effectively bounced back to the very start of the page.
try http://jsbin.com/sukevefepo/1/ just using the keyboard: TAB to the button, trigger it with ENTER/SPACE, then TAB to the close button, ENTER/SPACE. now, after the modal is closed, TAB...and you see that your focus is back on the very first link. for anything but the most simple pages, this is a major annoyance at best, and can be dramatically disorienting for screenreader users).
in short: current Bootstrap behaviour is correct. I understand the desire to neuter the focused appearance of the modal trigger once the modal itself is closed...but using blur() is not the answer (unless you care little about keyboard/AT users, that is).
a more robust approach, that I'm planning to investigate for future version of Bootstrap, is to dynamically set a class on the body once a user first navigates using TAB/SHIFT+TAB (indicating a keyboard user), and to suppress :focus styles for these situations otherwise.