Bootstrap 5 Modal
Open one labelled dialog, place focus deliberately and restore it to the trigger after Escape.
How it works
A modal interrupts the current page with a dialog task. It needs a clear title, a close route and a focus policy, not just a centred panel. Bootstrap supplies a focus trap and dismissal mechanics for its supported pattern. The HTML autofocus attribute does not solve focus timing inside a modal; use the shown lifecycle event when a specific initial field should receive focus. Avoid nested modals and do not hide a long essential reading task behind a dialog without a reason.
Run and inspect
Save the complete document as index.html in a separate lab folder. Place Bootstrap 5.3.8 CSS and the matching JavaScript bundle beside it. Open the file in a normal browser. A separate local static server is optional; no database or PHP execution is required. Keep the Bootstrap licence and bundled Popper licence with redistributed assets.
Download this complete HTML source.
This example needs the complete local setup with the Bootstrap JavaScript bundle. The restricted CSS playground does not reproduce this example’s full contract.
Example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 5 Treat a Modal as a Focus-management Boundary</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<main class="container py-4">
<h1 class="h3 mb-4">Repair day</h1>
<button id="open-modal" class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#repair-dialog">Open practice note</button><div class="modal" id="repair-dialog" tabindex="-1" aria-labelledby="dialog-title" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h2 id="dialog-title" class="modal-title fs-5">Practice note</h2><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close practice note"></button></div><div class="modal-body"><label class="form-label" for="modal-note">Local note</label><input id="modal-note" class="form-control"><p class="form-text mb-0">Nothing is saved or submitted.</p></div></div></div></div>
</main>
<script src="bootstrap.bundle.min.js"></script>
<script>
document.querySelector("#repair-dialog").addEventListener("shown.bs.modal", () => { document.querySelector("#modal-note").focus(); });
</script>
</body>
</html>
Expected result
The labelled dialog opens with focus in its input. Escape dismisses it and focus returns to the opener.
The shown event fires after the modal is ready for the focus move. The close button has an explicit accessible name. There is no pretend Save action: the example only demonstrates local dialog interaction. A production destructive confirmation must also explain consequences and define what happens if its underlying request fails.
Check Bootstrap’s official 5.3 documentation for component contracts and version details.