Reputation: 1087
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)
Upvotes: 4
Views: 3046
Reputation: 395
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:
Upvotes: 13