Sir Hally
Sir Hally

Reputation: 2358

javascript:void(0) or onclick="return false" for <a> - which is better?

There is a javascript-based interface - so I need not to support work without javascript.

I have an

<a>Something</a>

elements with JS code, which binds on click event - so, I don't want page reload after user's click.

Which way is better?

1. <a href="javascript:void(0)">Something</a>
2. <a href="#" onclick="return false;">Something</a>

What advantages and disadvantages of each method?

Upvotes: 14

Views: 59623

Answers (2)

Tim Down
Tim Down

Reputation: 324627

Neither. If your link doesn't go anywhere, don't use an <a> element. Use a <span> or something else appropriate and add CSS to style it as you wish.

Upvotes: 2

Delan Azabani
Delan Azabani

Reputation: 81422

Both are poor choices. Presentation shouldn't mix with content. That means no javascript: URIs, and definitely no onclick attributes.

The way to do it:

<a id="myLink">Something</a>
<script>
    function myFunction(...) { ... }
    document.getElementById('myLink').addEventListener('click', myFunction, false);
</script>

Upvotes: 11

Related Questions