Skip to content

Modal focus on close #41097

Answered by julien-deramond
palmem29 asked this question in Q&A
Dec 13, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

When data-bs-toggle="modal" is used, the code automatically gives back the focus to the element that triggered the modal. It's done in our code at

bootstrap/js/src/modal.js

Lines 352 to 356 in a353ed4

EventHandler.one(target, EVENT_HIDDEN, () => {
if (isVisible(this)) {
this.focus()
}
})

When you don't use data-bs, you'll have to do that manually. I've created a StackBlitz showing how to give back the focus in JS.

The code could be improved, but basically, it can be done like this:

(() => {
  'use strict';

  const btnSecondary = document.getElementById('btnSecondary');
  const exampleModal = document.getElementById('exampleModal');
  const myModal = new

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@palmem29
Comment options

Answer selected by palmem29
# for free to join this conversation on GitHub. Already have an account? # to comment
Category
Q&A
Labels
None yet
2 participants