call javascript function on hyperlink click

Neater still, instead of the typical href="#" or href="https://stackoverflow.com/questions/1265887/javascript:void" or href="https://stackoverflow.com/questions/1265887/whatever", I think this makes much more sense:

var el = document.getElementById('foo');
el.onclick = showFoo;


function showFoo() {
  alert('I am foo!');
  return false;
}

<a href="https://stackoverflow.com/questions/1265887/no-javascript.html" title="Get some foo!" id="foo">Show me some foo</a>

If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.

Leave a Comment