Skip to main content

Different ways to run a JavaScript function

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.