Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById('').focus() not working on button

I meet an issue when implementing accessibility features.

I tried to set keyboard focus on a button using the approach:

document.getElementById('123').focus()

But, it doesn't work. The element didn't get focused. Can I get some help? Thanks!

JS Fiddle: https://jsfiddle.net/dp5x7rbq/

like image 692
kevinzf Avatar asked Oct 16 '25 13:10

kevinzf


1 Answers

Actually, setting focus on the button already works in your example. You can verify which element has focus by checking document.activeElement.

The confusion is about the display or styling of the button’s focus state, which usually is a focus ring.

Make focus visible

Modern browser use :focus-visible pseudo-class to style elements that have focus. That selector takes into account whether the user should see focus or not, for example because they used the keyboard to set focus.

Since you are setting focus programmatically, that browser’s styling does not apply when the button has focus. You need to style the :focus pseudo-class yourself.

#btn123:focus {
  outline: 1px dotted #212121;
  outline: 5px auto -webkit-focus-ring-color;
}

See What is the default style of the blue focus outline in Chrome?

Use a valid ID

On a side note, the value 123 for an ID is invalid:

[…] an id must contain at least one character and may not contain any space characters.

See What are valid values for the id attribute in HTML?

like image 86
Andy Avatar answered Oct 18 '25 17:10

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!