8

If you want an event or a link to an empty javascript call, there are several ways, of which I can think of:

<a href="#">Method 1</a>                    <- Ugh... changes URL in browser
<a href="javascript:;">Method 1</a>         <- My currently preferred method
<a href="javascript:void(0);">Method 1</a>  <- Another approach?

What is the best way in terms of cross-browser compatibility and shortness?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • 3
    Counterquestion: I see no reasons to put an empty link onto a page? – Christoph Apr 15 '13 at 12:29
  • 6
    Links should... link to something. Even though it seems to be common to add event listeners to links, if it doesn't link to a fallback page if JavaScript is disabled., you should rather use buttons. – Felix Kling Apr 15 '13 at 12:30
  • As long as the event calls `preventDefault()` or returns false, `href="#"` doesn't change the browser URL. – JJJ Apr 15 '13 at 12:32
  • Sometimes I must use this. For instance, I have a clickable h2 that expands a container. I have to add an `a` tag around it for touch optimization. – bytecode77 Apr 15 '13 at 12:52

4 Answers4

6

Don't use links if they don't... well, link to anything.

Instead, use a span somewhat like this:

<span class="spanlink" onclick=something>This is some text</span>

And in your CSS:

.spanlink {
    text-decoration: underline;
    color: blue;
    cursor: pointer; /* Ragnagord's suggestion in comments */
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
3

A Jquery solution..

$('a.preventDefault').click(function(){
 return false
});

<a href="#" class="preventDefault">Method 1</a>
Blowsie
  • 40,239
  • 15
  • 88
  • 108
2

How about button? I never use anchors if they're not leading anywhere

CaptainCarl
  • 3,411
  • 6
  • 38
  • 71
0

Using unobtrusive Javascript.

Also, if a link doesn't do anything without Javascript, then a user without Javascript shouldn't even be able to see the link. Add in the link via Javascript.

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
  • Please avoid [link-only answers](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers). – ruakh May 20 '14 at 05:10