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?
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.
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.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With