Search code examples
bootstrap-4bootstrap-modalfocus

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.


Solution

  • 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();
    })