tobib
tobib

Reputation: 2444

use :focus as a :hover replacement for keyboard navigation

WCAG 2.0 recommends to also use :focus when :hover is used on link elements to support keyboard navigation. This works well for link elements, but there are a couple of differences between the two.

This question is strictly about css. Is there a way to simulate the behavior of :hover (as described above) for keyboard navigation? Or are there any strong reasons why one would not want that?

To make it more clear here is an example:

html:

<div id="box">
    foo bar
    <a href="#">click me</a>
</div>

css:

#box {
    opacity: 0.3;
}
#box:hover {
    opacity: 1;
}
#box a:focus {
    opacity: 1;
}

When using a mouse I will hover over the link element before using it. Since the :hover state propagates upwards #box will be fully opaque.

When using a keyboard I will focus the link element before using it. Since the :focus state does not propagate upwards #box will not be fully opaque.

Upvotes: 10

Views: 14738

Answers (3)

zıəs uɐɟəʇs
zıəs uɐɟəʇs

Reputation: 1793

A lot of time has past since the original question. Today we have :focus-within which should work nicely for cases like this one:

#box {
    opacity: 0.3;
}
#box:hover,
#box:focus-within {
    opacity: 1;
}

Upvotes: 4

tobib
tobib

Reputation: 2444

This can be done in JavaScript with focusin/focusout events (they are just like focus and blur except they bubble). Here is a fiddle.

It boils down to this function:

var deepFocus = function(element, cls) {
    cls = cls || 'deep-focus';

    element
        .on('focusin', function() {
            element.addClass(cls);
        })
        .on('focusout', function() {
            var value = !!element.find(':focus').length;
            element.toggleClass(cls, value);
        });
};

Update: There is a draft spec that contains the :focus-within selector which would exactly do what is required here.

Upvotes: 1

g.e.manor
g.e.manor

Reputation: 526

To make :focus effect on elemnts not link and form elements you need use in tabindex attributes. when you put it on each element you can assign it the :focus pesudo element.

in your example you need understand that opacity is stay on the parent div also if the link opacity change.

you can see working sample here. or sample to use tabindex

<div tabindex="1">Touch the Div</div>

Upvotes: 0

Related Questions