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?

4
  • 3
    Counterquestion: I see no reasons to put an empty link onto a page? Commented Apr 15, 2013 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. Commented Apr 15, 2013 at 12:30
  • As long as the event calls preventDefault() or returns false, href="#" doesn't change the browser URL. Commented Apr 15, 2013 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. Commented Apr 15, 2013 at 12:52

4 Answers 4

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 */
}
Sign up to request clarification or add additional context in comments.

5 Comments

I would add cursor: pointer; to the css.
This is not touch-friendly at all. That's the main reason I put links on everything clickable, even if they're not linking to another page.
@DevilsChild What do you mean by "touch-friendly"?
When you use a span and touch on it on a touch input device, your finger will select parts of the text, while it doesn't when using a link. Also, IE 10 highlights touched links, not touched spans.
It's impossible to interact with spans using the keyboard alone, this solution is not accessibility friendly.
3

A Jquery solution..

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

<a href="#" class="preventDefault">Method 1</a>

2 Comments

return false also prevents bubbling. Not the best idea.
@AlexeyLebedev Sure, but putting clickable elements inside <a> elements isn't a great idea either
2

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

Comments

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.

1 Comment

Please avoid link-only answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.