Different ways to run a JavaScript function

Sam Deering

I was looking back at some work and thought it would be good to do a post about different ways to load JavaScript functions (notably foo()) from inside HTML elements. Take a look below at some examples.

1 – anchor naked

  • Mouse cursor may not change on hover in some browsers.
  • CSS could be used to solve this problem: a {cursor:pointer; }
<a onclick="foo()"> ... </a>

2 – anchor hash href

  • Mouse hover shows link at #
  • Page may shift to top on IE6, IE7
<a href="#" onclick="foo()"> ... </a>

3 – anchor pseudo

  • Old school way of calling the function when the link is clicked.
  • Pseudo-protocols hrefs are not recommended for usability and accessibility reasons.
  • Nowdays considered back programming due to the influx of APIs available.
  • It’s messy, it’s long, people see it in the status bar and it means nothing.
  • Opera doesn’t like href=”javascript:[anything]“
<a href="javascript:foo()"> ... </a>

4 – anchor pseudo void

  • Using javascript:[anything] is considered by some to be bad practice.
  • Pseudo-protocol hrefs can cause IE to enable a waiting state anticipating the page to be replaced and automatically disable resource hungry activity.
  • javascript:[anything] is used for bookmarklets.
  • What is javascript:void(0);?
<a href="javascript:void(0)" onclick="foo()"> ... </a>

5 – anchor return false

  • Return false causes the href=”#” not to be evaluated.
  • Safer method than using Pseudo-protocols examples above such as page jumps.
  • Return can be unreliable at times.
<a href="#" onclick="foo(); return false;"> ... </a>

6 – anchor pretty url/jQuery

  • The use will see #some-real-url when they hover the link.
  • If JavaScript is disabled they see something informative.
<a href="#some-real-url" class="mylink"> ... </a>

$(document).on('click', 'a.mylink', function(e)
{
     //prevent the page from going to href
     e.preventDefault();

     //run the function
     foo();
});

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • blitzkid

    Thanks for this post!

  • /User/Reg

    great work.

  • Christopher Jazinski

    Which way is the most widely used and why? I’ve mixed and matched all of them..