views:

708

answers:

4

I have an anchor that doesn't go anywhere but has an onclick (e.g. <a onclick="..."></a>). My question pertains to the href attribute. What should I put for the value?

If I simply omit href, the anchor doesn't have the appropriate decoration--the mouse pointer icon doesn't change when the mouse is put over it.

If I use href="#", then the window scrolls to the top of the page when the link is clicked.

If I use href="javascript:..." and put the value of onclick proceeding javascript:, the page is left and the address bar contains the Javascript when the link is clicked.

When I refer to browser behavior, I'm referring to Chrome, which I'm testing it in to start with.

What should I be putting for href when the anchor isn't an actual link but exists only to have the onclick perform behavior?

+9  A: 

Ideally you would have an option for those with Javascript disabled:

<a href="degrade_option.html" onclick="return fancy_option();">do the option!</a>

If you're not into that sort of thing, although you really should be, the most common way is to use the pound but then cancel the event to prevent the default action from happening, like so:

<a href="#" onclick="return do_something();">do something</a>

But then you have to make sure do_something returns false. (or you can just add return false; at the end of the click handler, but this gets even more unsightly fast)

Although, to be honest, you really shouldn't have inline Javascript attributes to begin with. They are bad practice, a nightmare to maintain, and there are much better alternatives out there.

EDIT: In response to your comment, the alternative is unobtrusive javascript:

"Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include:

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

Read the page for some examples.

Paolo Bergantino
And what are the alternatives?
Chris
+4  A: 

In your onclick handler, add this to the end:

return false;

This will cancel the default processing (i.e. following the link) and you can put whatever you want in the href (the # is as good as any).

Jon Grant
A: 

Have you tried this?

javascript:void(0);

Edit: For what its worth, the following works just fine in Google Chrome 2.0:

<div class="center"> 
    <a href="javascript:void(0);" class="forumButton" onclick="window.close();">Close</a> 
</div>
jrummell
I'll take that down vote as a no ...
jrummell
A: 
<a href="javascript:void(0);" onclick="...">txt</a>
Colin