"javascript:;" for href attribute in HTML anchor tag

html, javascript

Solution

Using "javascript:" as the start of a href attribute to a link tells the javascript engine to use the rest of the string to be interpreted as javascript. In this case, it would cause a syntax error in strict interpretation, since this is effectively an empty javascript line with a closing semicolon. Like this:

;

Most browsers won't throw an error, however, as javascript on links are old syntax and should be avoided when possible. You could safely use it as a link that does nothing, however I wouldn't recommend it.

If you want a link to do nothing, you could use this instead:

<a href="#">Link</a>
<a href="javascript:void(0);">Link</a>
<a href="javascript:return false;">Link</a>

Using an empty href string will make the browser interpret it as a relative link. URLs that don't start with a protocol or an identifier like a high level domain or IP address will be treated as relative links. For example, the link `"index.htm"` on the domain `"google.com"` will create the link `"google.com/index.htm"`. In the same way, the href string `""` will create the link `"google.com/"` and so empty href strings will cause the browser to navigate to a new page.

Normally a link will not show the pointer cursor or format the element like a link if you do not specify a href attribute, this is so you can use it as an "anchor" element that you can link to using the hash character in a URL. Such as `"http://google.com/#an_anchor"` will take you to an anchor similar to this: `<a id="an_anchor">This is an anchor</a>`

However you can use CSS to force the link to be formatted, like this:

CSS:

a {
    color: #00c;
    text-decoration: underline;
    cursor: pointer;
}

HTML:

<a>This is a link.</a>

Example: http://jsfiddle.net/J3RfH/

Problem

Update What does the code below mean and do? It needs JavaScript to work? ``` <a href="javascript:;">Do Somthing</a> ``` Update Is equal to below?: ``` <a href="">Do Somthing</a> ```

Original source