Search code examples
htmlcssaccessibilitywai-ariatabindex

How to change values of tabindex and aria-hidden depending on browser size?


For desktop browser sizes I have a navbar across the top of the page, when browser reduces to mobile size it becomes a hamburger menu. As the menu is hidden at mobile size, then for accessibility reasons I believe that, the elements within the menu need to have attributes of tabindex=-1 and aria-hidden=true. The website is being built using HTML/Jinja2, CSS, client side JS and Python/Flask.

As you can see from the CodePen below I am able to toggle the aria-hidden attribute once the menu has been opened.

[My demonstration repsonsive menu using CodePen] (https://codepen.io/janlikescodepen/pen/wvJmdBZ)


Solution

  • For anyone stuck on a similiar problem - wanting to creating a simple dropdown menu that does not disrupt the tabindex flow and screenreader flow, then my solution to this problem is using simple CSS + JS. The steps for it are:

    1. At the mobile breakpoint the menu is hidden using display:none; and the hamburger is displayed
    2. Clicking the hamburger calls a JS function that adds a CSS class to the menu that causes menu to be displayed because the class has display:flex and is lower down the stylesheet than the CSS style mentioned in step 1, therefore overriding it.
    3. Clicking the hamburger calls the same JS function, but this time removes the class that was added in step 2, thus hiding the menu.

    As suggested by QuentinC and Graham Ritchie, I used display:none instead of height:0 to hide the menu because this solves the issues for keyboard only or screenreader users.

    [View demo code in Codepen.][1] [Codepen]

    Notes:
    If you are thinking of using JS to toggle display:none/display:flex, then I warn you that you might face some specificity issues. This was my initial attempt, but I encountered specificity issues that I could only resolve by using !important. Simply adding and removing a class, as per my example, does not create specificity issues because there is no inline styling or html ID.
    [1]: https://codepen.io/janlikescodepen/pen/yLMKxZB