🤯 50% Off! 700+ courses, assessments, and books

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

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