What is the difference between href=""
, href="#"
and href="javascript:void(0)"
?
What are the different uses for them and when is one better than another?
Definition and Usage. The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!
(Hypertext REFerence) The HTML code used to create a link to another page. The HREF is an attribute of the anchor tag, which is also used to identify sections within a document.
href=""
will reload the current page
href="#"
will scroll the current page to the top
`href="javascript: void(0)" will do nothing.
You can get the same effect of javascript: void(0)
by returning false from the click event handler of the anchor with either of the other two methods as well.
I prefer to use <a id="the-link" href="#">Link</a>
and then bind an event handler to the click listener somewhere in my javascript like:
document.getElementById('the-link').onclick = function(){
// Do stuff
return false;
};
This way, since you're using #
, even if the user has javascript disabled the page won't reload (it will just scroll to the top), and I think it's a lot cleaner looking than javascript: void(0)
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