Often people need links which are not linked directly, but should trigger execution of JavaScript.
You can find a lot of workarounds for that:
<a href="#">Do something with js!</a>
This defines an empty anchor. This may lead the browser to let the page jump to the top when the link is clicked, unless you call preventDefault
on the event. This is probably not what you want.
<a href="#!">Do something with js!</a>
This tells the browser to jump to an anchor !
. It depends on the browser implementation what happens when an anchor with unknown target ist clicked. In the best case it just does nothing.
<a href="javascript:void(0)">Do something with js!</a>
This might violate your Content Security Policy directives. See this card for info on how to avoid that.
<div class="my-trigger">Do something with js!</div>
This will probably work, but div
and span
are not in the tab order and a someone using a screenreader will have a hard time using your page.
Do not use the hacks above. Instead, use the HTML element which was meant for that:
<button type="button">Do something with js!</button>
and style it like a link if you want it to look like a link.
Note
Read the card Accessibility: Making non-standard elements interactive for more details of this approach. It includes various implementation variants depending on the given technology stack and use case.