Adding WAI-ARIA support to jQuery .toggle() method

2019-06-24 01:13发布

I'd like to pair WAI-ARIA aria-hidden support with jQuery's .toggle() method.

So given <p id="myElement">Hi there</p>

$('#myElement').toggle() would hide the element, and set aria-hidden="true":

<p id="myElement" style="display: none;" aria-hidden="true">Hi there</p>

And executing the same $('#myElement').toggle() script again would show (toggle) the element, and set (toggle) aria-hidden="false":

<p id="myElement" style="display: block" aria-hidden="false">Hi there</p>

I probably want to use the complete function of the method, maybe something along the lines of

$('#myElement').toggle(
    if ($this.css('display')==='none'){
       $this.prop('aria-hidden', 'true')
    }
    else
    {
            $this.prop('aria-hidden', 'false')
    }
)

What's the most performant solution for extending .toggle() to also toggle the aria-hidden state?

2条回答
男人必须洒脱
2楼-- · 2019-06-24 01:36

The accepted answer is correct in spirit, but has some problems in specifics:

  1. There is no 'hidden' value for the CSS Display property--it should be 'none'.

  2. jQuery .toggle() doesn't set the display to 'inline' when un-hiding; it sets it back to blank, which falls back to whatever value is dictated by the cascade. So if the computed value for display was 'block', that's what it returns to.

查看更多
何必那么认真
3楼-- · 2019-06-24 01:51

The short answer is that there's no need to do so.

Accessible Technology supports CSS's display: hidden; property in a way that already properly hides the element. So specifying aria-hidden="true" is redundant, from a screen-reader's point of view, to jQuery's .toggle() method setting the display property to hidden. Specifying aria-hidden="false" (or removing the aria-hidden property) is redundant to jQuery's .toggle() method setting the display property to inline.

Please see https://stackoverflow.com/a/10351673/1430996 and Steve Faulkner's HTML5 Accessibility Chops: hidden and aria-hidden blog post (particularly the "Results Summary") for further details.

查看更多
登录 后发表回答