I have a modal with two buttons: one in the header and one in the modal body. Currently, when the modal opens, the focus automatically goes to the button in the modal body, but I want it to focus on the header button.
To address this, I wrote a function that adds an event listener to the modal button, and within that function, I included the code to focus on the header button.
My code is as follow:
triggerBtn(){
const modalBtnDiv = document.querySelector('.modal-div');
const headerBtn = document.querySelector('.header-btn');
const myFocusEvent =(e) =>{
headerBtn.focus();
modalBtnDiv.removeEventListener('focus', myFocusEvent);
};
modalBtnDiv.addEventListener('focus', myFocusEvent);
}
However, the issue is that focusEvent() is triggered only once. When triggerBtn() is called again, focusEvent() doesn’t work because, after the listener is removed, it isn’t being reattached. And if I don’t remove the event listener, the focus stays on header btn and does not go to the next button.
Is there a way to resolve this and ensure the focus works as intended?
2
Answers
As far as I understand your question, you want to autofocus on the button in the header. This can be achieved by adding
autofocus
to the button in your HTML template like so:And then you can get rid of the function
triggerBtn()
If you do need it to be set via the
triggerBtn()
function, you can achieve the same results by adjusting your function a little bit:Hope this helps!
If you are accessing the btns from a library( I assume you have access to the library code ), you can write a common directive for the btns in the library (example : focus-btn) and use it to focus. You can access the element using elementref from angular core.
I hope this helps.