Read more

Triggering JavaScript when an element is clicked

Judith Roth
August 13, 2021Software engineer at makandra GmbH

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

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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.

So what is a better solution?

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)

See also

Posted by Judith Roth to makandra dev (2021-08-13 17:41)