To ' href="javascript:f()" ' or ' href="#" onclick="f()" ' – That is the question.

You see both of these methods being used so often that you have to wonder – which is correct?

href=”javascript:f()”

vs

href=”#” onclick=”javascript:f()”

The classic ill side-effect that can occur when using the javascript: within a href attribute is when the function returns a value. Eg when opening a new window using window.open() – it returns an object reference to the new windows. In some browsers this will redirect to an otherwise blank page except for the word “[object]” (IE) or “[object Window]” (Netscape 4.x). However, assigning the window.open method to a variable avoids this. So:

href=”javascript:window.open();” will redirect the opener to [object] or [object Window]

href=”javascript:var newWin = window.open();”  will pop the window without an opener redirect

Another trick is to wrap the function call in void as follows. href=”javascript:void(window.open());”

However, I believe that best practice is placing the target URI in the href attribute (like a normal link) or some descriptive text and placing the javascript in an onclick event handler (with the addition of “return false” at the end to cancel the link’s default behavior).

When you use “return false” on onclick eg. onclick=”functionName();return false” the browser doesn’t try to go to whatever is specified in the href when the link is clicked. If the onclick calls a submit function then you have effectively asked the browser to go to the href and the action of whatever form you are submitting.

So this is probably the best of both worlds.

href=”javascript://Open A New Window” onclick=”window.open();return false;”

Other possibilities for the href are

javascript:void()

javascript:

#

javascript://This Is Safer

 

Advertisements

About metawrap

CTO Massive Interactive. Ex Computer Whiz Kid - Now Grumpy Old Guru.
This entry was posted in Downtime, JavaScript, Rants. Bookmark the permalink.

4 Responses to To ' href="javascript:f()" ' or ' href="#" onclick="f()" ' – That is the question.

  1. MarbleMad says:

    thanks a lot for this info !!

  2. Sanjiv Jivan says:

    Very useful indeed. Thanks!

  3. Jose Martinez says:

    Great Info. Saved me a lot of time.
    Thanks a lot.

  4. Millie says:

    Thanks, this was exactly what I needed. Very helpful

    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s