Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty-linked anchor

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?

like image 231
core Avatar asked Jul 27 '09 19:07

core


Video Answer


1 Answers

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.

like image 96
Paolo Bergantino Avatar answered Sep 21 '22 01:09

Paolo Bergantino