bootstrap-modalwai-aria

How to handle form close on cancel?


I have a modal form made with Bootstrap, and when the user clicks the cancel button I get a warning in the console:

locked aria-hidden on an element because its descendant retained focus...

This is because the cancel button retains focus when the modal dialog goes away. How do I add a callback to the form to handle the user clicking the cancel button, or hitting escape?


Solution

  • Bootstrap provides events like:

    You can hook into these to detect when the modal is closed by any method (Cancel button, Escape, backdrop, etc.).

    const myModalEl = document.getElementById('myModal');
    
    myModalEl.addEventListener('hide.bs.modal', function (event) {
        console.log('Modal is closing');
        // Handle cancel logic here
    });
    
    myModalEl.addEventListener('hidden.bs.modal', function (event) {
        console.log('Modal fully hidden');
        // Optionally restore focus to a safe element
        document.getElementById('some-safe-button').focus();
    });