0

Suppose I want to use an <a> link for a toggle in Svelte/SvelteKit. For example:

<a on:click|preventDefault={_=>collapsed=!collapsed}>Toggle</a>

I get this warning from my VS Code plugin:

A11y: <a> element should have an href attributesvelte(a11y-missing-attribute)

What's an appropriate choice for href? If I try # or javascript:void(0) as suggested at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"? I am told:

A11y: '#' is not a valid href attributesvelte(a11y-invalid-attribute)

Steven Clontz
  • 945
  • 1
  • 11
  • 20
  • In my app using SvelteKit with a static site adapter, using `href="./"` seems to behave reasonably and not raise any warnings. (I'd prefer an answer that explains more of the rationale for this warning, particularly why leaving off `href` altogether isn't acceptable.) – Steven Clontz Mar 16 '23 at 18:42

1 Answers1

8

The question is not specific to Svelte. It is only that the Svelte compiler gives you a hint that you are using the wrong element.

A link is supposed to lead you to another resource. Your "link" changes something in the same page and thus should be a button. So when you write

<button on:click={_=>collapsed=!collapsed}>Toggle</button>

there won't be an accessibility warning. If the button does not look as you like, change its apperance with CSS - keeping accessibility of course (such as focus outlines).

Generally speaking, when you have a link and want to use a "empty" href attribute, you are probably using the wrong element. This is why also most of the answers at the linked question are wrong. (It is really sad that they are not marked as such, and the many upvotes are even more misleading.)

It is also worth noting that you will get an accessibility warning when you use a div here:

<div on:click={_=>collapsed=!collapsed}>Toggle</div> (DO NOT DO THIS)

The warning by the compiler is:

A11y: visible, non-interactive elements with an on:click event must be accompanied by an on:keydown, on:keyup, or on:keypress event. svelte(a11y-click-events-have-key-events)

But instead of implementing these events, just use a button which has all the required accessibility features built-in.

Suggested resources:

Script Raccoon
  • 261
  • 2
  • 14
  • Thanks. As a bonus, I think the UI is improved for the purpose I'm currently working on with the button styling vs. appearing as a link. I'm not using any CSS framework for this project, but I suppose this is why e.g. Bootstrap has support for a btn-link class: https://getbootstrap.com/docs/5.0/components/buttons/#examples – Steven Clontz Mar 17 '23 at 13:22