alex
alex

Reputation: 611

Bootstrap Modal should return focus to last focused element after closing

I have focusable table rows, which on trigger open a Bootstrap Modal. However I noticed that whenever I close said Modal, the focus seems to disappear entirely and starts back in the beginning.

Is there an easy way to prevent this?

If not, I was thinking of possibly storing the ID of the last focused element in a variable right as the modal gets opened, and then refocusing after the modal is closed, but I only found the option to trigger events after the Modal already opened, at which point the element isn't focused anymore.

Upvotes: 2

Views: 1388

Answers (1)

alex
alex

Reputation: 611

I found a solution. I save the last focus on the show.bs.modal Event and then focus back on it after the modal is hidden with the hidden.bs.modal event.

    var lastFocus;
$('.modal').on('show.bs.modal', function (e) {
    lastFocus = $(':focus');
})
$('.modal').on('hidden.bs.modal', function (e) {
    if(lastFocus)
        lastFocus.focus();
})

Upvotes: 1

Related Questions