Different ways to run a JavaScript function

By 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; }

2 – anchor hash href

  • Mouse hover shows link at #
  • Page may shift to top on IE6, IE7

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]”

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);?

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.

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.

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

     //run the function

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • 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..

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.