Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the focus on a javascript modal window?

Our website involves some javascript that produces overlay modal windows.

There is one accessibility problem with this though, once the modal is triggered, the focus is still on the trigger element and not on the modal itself.

These modals can include all sorts of html elements, headings, paragraphs and form controls. What I would like is the focus to begin on the first element within the modal, so most likely to be a h4 tag.

I have explored using the focus() function however this does not work with a number of html elements.

One thought was to add an empty a tag in the window which could gain the focus, but I am unsure about this method.

like image 769
user502014 Avatar asked Nov 16 '10 15:11

user502014


1 Answers

very late to the party, but the existing answers do not respect accessibility.

The W3C wiki page on accessible modals offers more insight than what's asked in the OP, the relevant part is having tabindex=-1 on the modal container (which should also have an aria-dialog attribute) so it can get :focus.

This is the most accessible way of setting the focus on the modal, there is also more documentation about keeping it in the modal only - and returning it to the element that triggered the modal - quite a lot to be explained here, so I suggest anyone interested to check the link above.

like image 94
Luca Avatar answered Oct 12 '22 20:10

Luca