<legend> won't receive :focus event?

725 Views Asked by At

Here is the HTML:

              <fieldset>
                <legend>FieldsetName</legend>
                <div></div>
              </fieldset>

Here is the CSS:

legend:focus {
  background-color: #ffddbe;
  outline: none; 
}
legend.focusin {
  background-color: #ffddbe;
  outline: none; 
}

Clicking on it doesn't do anything.

OK, I thought, I'll go with jQuery.

$('legend').focusin( function() {
    $(this).addClass('focusin');
    });

$('legend').focusout( function() {
    $(this).removeClass('focusin');
});

It doesn't help either. However, if $('legend') listens to "click", it does what it is supposed to do. What gives?

2

There are 2 best solutions below

3
Arun P Johny On BEST ANSWER

Not sure whether it is the correct fix, but adding a tabIndex fixes it

<legend tabIndex="1">FieldsetName</legend>

Demo: Fiddle

0
depiction On

It's best to use tabindex="0".

<legend tabindex="0">FieldsetName</legend>

Here's a breakdown of possible tabindex values and use cases:

  • tabindex="0" allows an element to receive focus in the order that it appears in the DOM.
  • tabindex="1" (or any number greater than 1) defines an explicit tab order. This is almost always a bad idea.
  • tabindex="-1" allows elements besides links and form elements to receive focus programmatically