Triggering JavaScript when an element is clicked

Updated . Posted . Visible to the public.

Often people need links which are not linked directly, but should trigger execution of JavaScript.

❌ Bad workarounds

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.

✔️ Better solution: Use a fitting native HTML element

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.

  • This is good for screen readers, which can differentiate between buttons and links
  • Buttons are in the tab order of a browser
  • By default, buttons bring hover and focus states (although you probably will not want to use these styles and instead apply your own styles)

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.

See also

Judith Roth
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2021-08-13 15:41)