Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 506
Sir Hally Avatar asked Aug 12 '10 07:08

Sir Hally


People also ask

Should I use JavaScript void 0?

Combining javascript: and void(0) Sometimes, you do not want a link to navigate to another page or reload a page. Using javascript: , you can run code that does not change the current page. This, used with void(0) means, do nothing - don't reload, don't navigate, do not run any code.

What can I use instead of JavaScript void 0?

There's no real alternative to `javascript:void 0`. If you need to have a link that absolutely will not do anything, even under noscript, it's the only solution. Using `href="#"` is not an alternative, because it messes with the user's navigation history.

Which href value should I use for JavaScript links or JavaScript void 0?

The href= “” will only load the current page, while href= “#” scrolls the current page to the top, while href= 'javascript:void(0)' will do nothing at all. The same effects of javascript:void(0) are realized by returning false from the click event handler of the <a> tag with either of the two methods.

What is return false in Onclick?

using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute. In other words, adding return false stops the href from working. In your example, this is exactly what you want.


2 Answers

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>
like image 185
Delan Azabani Avatar answered Sep 21 '22 19:09

Delan Azabani


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.

like image 26
Tim Down Avatar answered Sep 23 '22 19:09

Tim Down