Is it preferable to have #
in a link’s href
attribute when I am implementing the click
event via jQuery, or is it ok to leave href
empty?
i.e.
<a id="myLink" href="#" />
vs
<a id="myLink" href="" />
When I’m doing
$("#myLink").on('click', function() {
// do ajaxy stuff
});
Although I understand the click event could be on a span or other such element I’m interested in this case for particular best practices when using an a
tag.
Links with an empty href
attribute are valid, as explained in RFC2396:
4.2. Same-document References
A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML’s FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request.
It’s not really an issue significant enough to be anything more than personal preference. Personally, I’d go with a third option:
<a id="myLink" href="<url>" />
…where <url>
is the url of my ajax request. Obviously that introduces a step in jQuery:
$("#myLink").click(function(event) {
event.preventDefault();
url = $(this).attr("href");
// do ajaxy stuff
});
…but I find it a bit more convenient than hardcoding the url in Javascript, it makes sense semantically (checking your code couple of years after you wrote it, the url will be were you’ll first look for it – probably). It’s also a neat trick if you have a few simplistic ajax-y links that do more or less the same thing. Consider this example:
<a class="ajax" href="<url1>">
<a class="ajax" href="<url2>">
<a class="ajax" href="<url3>">
$("a.ajax").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$.get(url, function(data) {
console.log(data);
});
});
4
I don’t think it’ll make a huge difference most of the time. If there’s no real link, you might also consider using a span instead of an a tag.
I’ve seen something like this as well:
<a id="myLink" href="javascript:void(0)" />
See this page for examples: http://weblogs.asp.net/joelvarty/archive/2008/09/30/javascript-in-lt-a-gt-tags-vs-javascript-void-0.aspx
Additionally, it would be a good idea to run the html through a validator to check for any potential problems.
1
Yannis’ answer is a good one, but I still don’t know why anyone would need to use <a href…> tags for events at all. You can use pretty much any tag you can throw an id into for events, thereby removing the whole ‘href=”” is legal’ discussion or employing code to prevent the link being followed.
On the other hand, if it’s a link then use <a href=”…”>
1