1535
<a href="javascript:void(0)" id="loginlink">login</a>

I've seen such hrefs many times, but I don't know what exactly that means.

Ondra Žižka
  • 36,997
  • 35
  • 184
  • 250
omg
  • 123,990
  • 135
  • 275
  • 341
  • 16
    `javascript:` is one of the many URI schemes: http://en.wikipedia.org/wiki/URI_scheme, like `data:`. – Ciro Santilli新疆棉花TRUMP BAN BAD Aug 23 '14 at 21:05
  • 7
    You can use just `href="javascript:"` for the same purpose. As stated in the answer for [this question](http://stackoverflow.com/q/5237105/3075942), the `void(0)` part was originally intended for early versions of browsers where `javascript:` URI handling was different. But now I couldn't even find a version where the shorthand wouldn't work, at least IE7 handles this correctly. – user Apr 05 '15 at 03:24
  • 1
    I've also seen href="javascript://", is this better? – lightsaber Dec 30 '16 at 13:43
  • href="javascript://" is not working for me void(0) works perfectly. – sandip Jun 03 '17 at 08:20
  • @sandip Which browser did you use back then? `href="javascript://"` and `href="javascript:void(0)"` are equivalent. `//` is a JS comment. – Sebastian Simon May 29 '21 at 01:25

14 Answers14

1143

The void operator evaluates the given expression and then returns undefined.

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

An explanation is provided here: void operator.

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

Yona Appletree
  • 7,618
  • 6
  • 31
  • 44
rahul
  • 174,563
  • 47
  • 223
  • 254
  • 15
    what does it mean when href is given a "undefined primitive value"? – omg Aug 18 '09 at 05:32
  • 12
    "normally a javascript: url will redirect the browser to a plain text version of the result of evaluating that javascript. " Can you make an example here?I've never seen such usage. – omg Aug 18 '09 at 05:40
  • if your write a javascript function on onclick and if the javascript functin returns false then this false will be shown in the browser – rahul Aug 18 '09 at 05:42
  • And, isn't javascript:void() more convenient to achieve that goal? – omg Aug 18 '09 at 05:45
  • 100
    An example of what phoenix is talking about is DO IT NOW! . If dosomething returns false, then clicking the link will simply cause the browser to exit the page and display "false". However... DO IT NOW! avoids the problem. Go ahead and paste javascript: 1+1; into your browsers address bar. The browser should display "2" – Breton Aug 18 '09 at 05:50
  • @Breton ,thank you.Got it. But why don't we use "javascript:void()",I mean,why is "0" needed here? – omg Aug 18 '09 at 05:52
  • 10
    Because void is a unary operator. Void is not a value, nor is it a function. It needs a value to operate on to its right, or it will throw an error. – Breton Aug 18 '09 at 05:59
  • 15
    try looking in the error console? It definetely throws a syntax error. It's invalid javascript. Douglas crockford reccomends staying away from void because of the unary operator/function/value confusion is too costly to deal with. – Breton Aug 18 '09 at 06:05
  • read this [answer](http://stackoverflow.com/a/1293130/1936980) below, it clarifies things beautifully. – Raghav May 19 '13 at 09:11
  • may be, it can be simpler to use the javascript; – Konstantin Isaev Apr 07 '14 at 21:40
  • Maybe worth noting - undefined is not writable variable, as seen in first link of this answer. – NoBugs May 21 '14 at 05:20
  • What's wrong with "javascript:undefined", it seems to work in the same way. – TigOldBitties May 07 '15 at 11:52
  • Aside from whether it is right or wrong, this post does not really answer *how* `javascript:void(0)` style links work. Presumably, that is quite related to the question. – jpaugh Oct 16 '15 at 03:06
  • 1
    Although I almost always use `href="#"` (with the now available `e.preventDefault()`), why don't we all just style a span/p/div? It seems much easier and less of a javascript hassle. By what I have found, an "a" and a "span" are identical with defaults except for the color and the fact that "a" can contain a link. – ZomoXYZ Jan 25 '16 at 15:10
  • 2
    "`void 0` is the smallest possible"... would it work using `[][0]`? It also evaluates to undefined. (this and `null` seems to work on Chrome, not sure on other browsers) – BrunoLM Jan 02 '17 at 16:02
  • @Breton Not anymore on Microsoft Edge, it now blocks inline javascript, no matter in the URL box or in href attribute of . – Happypig375 Aug 30 '17 at 06:18
  • @BrunoLM I had the same thought, but `0[0]` is actually shorter, and also evaluates to undefined. It's also so much more readable than void(0) /s – Yona Appletree Sep 28 '17 at 01:56
  • When I typed `javascript:"

    Surprise!!

    "` in my address bar, it was a small surprise that it rendered as html. An even bigger surprise was that the address bar stayed on the same page, even after clicking the link (Chrome only. Edge changes the address bar initially but not when clicking the link).
    – Qwertie Jun 20 '18 at 20:59
  • Void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling. Void(0) is used to call another method without refreshing the page. – pranabesh chand Jan 26 '19 at 07:47
  • But `javascript:;` works too (no errors), and it's easy to understand that it means "do nothing". Why is it not used? – MaxiMouse Jul 27 '19 at 13:00
  • IMHO, I prefer `javascript:void(0)` :D – Momoro Jan 29 '20 at 07:39
  • @Jaketr00 You shouldn't use a span/p/div unless you also specify a tabindex. There are too many sites that do that, and it's annoying because the links get skipped in the tab order. – programmer Mar 12 '20 at 15:12
466

In addition to the technical answer, javascript:void means the author is Doing It Wrong.

There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.

<a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.

In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.

Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what StackOverflow [did at the time of writing; now it uses href="#"].

The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).

If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.

(*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)

bobince
  • 498,320
  • 101
  • 621
  • 807
130

It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

You should actually just return false in the onclick event, like so:

<a href="#" onclick="return false;">hello</a>

Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>
Rory O'Kane
  • 25,436
  • 11
  • 86
  • 123
Noon Silk
  • 51,625
  • 6
  • 84
  • 103
  • href="#" will add a "#" to the url,which is ugly. – omg Aug 18 '09 at 05:35
  • It not only adds # to the url but also takes the focus to the top of the form. – rahul Aug 18 '09 at 05:38
  • 35
    no no - return false will stop the default behavior, so the # will never appear – Magnar Aug 18 '09 at 05:43
  • 1
    Phoenix and shore: return false will prevent the link from ever evaluating. It won't go anywhere, nor will it change focus to the top of the page. – Noon Silk Aug 18 '09 at 05:45
  • Ok,but I still like the void version better,since it won't bother onclick attribute,all in a nutshell. – omg Aug 18 '09 at 05:49
  • 1
    shore: that's your preference. but it's not the 'correct' way. – Noon Silk Aug 18 '09 at 05:50
  • @silky, I'm just curious what makes it the 'correct' way? I'm not saying you're wrong, because I do it the way you've mentioned, but I do it just because thats the way I learned to do it. Is this actually based off a standard or something? – Brandon Aug 18 '09 at 05:53
  • 22
    the javascript: url protocol is a defacto standard, not a real standard. So the href="#" onclick="return false;" is standards compliant while href="javascript:void(0)" is not, because there is no official standard that specifies what that should do. – Breton Aug 18 '09 at 05:55
  • 10
    On top of that, Douglas Crockford doesn't like void, so jslint will complain about it. Basically, since void is an operator, and not a value, it's confusing as hell, and spawns many questions such as this one. Better to avoid it altogether. haha. – Breton Aug 18 '09 at 05:57
  • 4
    Brandon: see brenton's responses. The way I recommend is the most supported and as I said in the second part of my post, in a 'proper' site you won't ever even use '#', because you'll be providing fallback systems to handle a lack of javascript. – Noon Silk Aug 18 '09 at 06:00
  • 21
    +1 for including the *completely awesome* example. Even if you have no static HTML fall-back for what you're doing in JavaScript, you can always do something like ``. – Grant Wagner Aug 18 '09 at 18:29
  • 2
    You should never ever ever `return false`, and you should rarely, if ever, use inline JavaScript. This answer was written 5 years ago when many now-accepted web design processes weren't invented yet, so these were seen as OK. Although I guess, even now, they aren't as bad as `href="javascript:void:0"`. – trysis Jul 26 '14 at 00:46
  • 1
    In event handlers, `return false;` does both `event.preventDefault();` and `event.stopPropagation();`. It's usually better to be explicit. Perhaps I shouldn't have said "never ever", or maybe I should have said "never ever in production". Just be careful and be sure you are OK with doing both. – trysis Jan 23 '18 at 13:33
84

It is a very popular method of adding JavaScript functions to HTML links.
For example: the [Print] links that you see on many webpages are written like this:

<a href="javascript:void(0)" onclick="callPrintFunction()">Print</a>

Why do we need href while onclick alone can get the job done? Because when users hover over the text 'Print' when there's no href, the cursor will change to a caret (ꕯ) instead of a pointer (👆). Only having href on an a tag validates it as a hyperlink.

An alternative to href="javascript:void(0);", is the use of href="#". This alternative doesn't require JavaScript to be turned on in the user's browser, so it is more compatible.

Gust van de Wal
  • 4,519
  • 18
  • 39
82

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

Aryan Beezadhur
  • 2,647
  • 1
  • 12
  • 31
Salvin Francis
  • 3,907
  • 4
  • 32
  • 43
  • 29
    @Salvin: The *scroll-to-top-of-page* behavior can be suppressed by returning `false` to the event handler: `onclick="doSomething();return false;"`, or if `doSomething()` returns `false`, you can use `onclick="return doSomething();"`. – Grant Wagner Aug 18 '09 at 18:25
  • 48
    @GrantWagner - Or, 5 years later, `e.preventDefault()`. – trysis Jul 26 '14 at 00:47
  • 1
    You might want to edit/delete this answer since `"#"` does *not* scroll to the top when you return false. – Navin Oct 30 '15 at 06:06
  • 4
    @Navin you are correct, but that is now an outdated practice. The comment by trysis is considered the correct way now. – Tim Seguine Nov 12 '15 at 15:15
  • @trysis Or, in inline html, use `event` for `e`. The `event` variable is available inside inline html `onclick` handler. `...` – STEN Jun 27 '20 at 05:41
49

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jscharf
  • 5,480
  • 2
  • 20
  • 16
31

It's worth mentioning that you'll sometimes see void 0 when checking for undefined, simply because it requires fewer characters.

For example:

if (something === undefined) {
    doSomething();
}

Compared to:

if (something === void 0) {
    doSomething();
}

Some minification methods replace undefined with void 0 for this reason.

Aryan Beezadhur
  • 2,647
  • 1
  • 12
  • 31
Squall
  • 661
  • 7
  • 8
  • 11
    One notable example is TypeScript ([live example](http://www.typescriptlang.org/play/#src=function%20fn(value%3A%20number%20%3D%207)%20%7B%0D%0A%20%20%20%20return%20value%20*%202%3B%0D%0A%7D)), which compiles default parameter values to checks against `void 0`. The 3 character difference adds up quickly when lots of methods are using default param values. – John Weisz Jan 16 '17 at 11:26
  • 1
    "Some minification methods replace undefined with void 0 for this reason." Finally I understand it! Thanks @squall for the thorough answer. – Ahmed Mahmoud Nov 21 '18 at 12:10
  • @ΛRYΛN That is not correct. Your code also does something on `false`, `0`, `""` and a bunch of other things. – akauppi Dec 30 '20 at 13:14
27

Usage of javascript:void(0) means that the author of the HTML is misusing the anchor element in place of the button element.

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

Source: MDN's <a> Page.

Styx
  • 8,485
  • 8
  • 36
  • 46
Ronnie Royston
  • 11,959
  • 5
  • 57
  • 72
  • 6
    +1 for bringing up semantic html on an old question... Links go places, buttons do things - if we don't want it looking like a button, we should just clear the styling. – kevlarr Oct 11 '17 at 17:14
  • The big exception to this would be image maps, which may need to execute JavaScript; and since it is not a button, it is a link that has polygonal bounds, this is the "only" way. –  Apr 28 '18 at 06:16
20

void is an operator that is used to return a undefined value so the browser will not be able to load a new page.

Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:

<a href="javascript: alert('Hello World')">Click Me</a>

then an alert message will show up without loading a new page, and that is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:

<a href="javascript: void(0)">I am a useless link</a>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Amr
  • 3,978
  • 6
  • 39
  • 55
  • 1
    I have seen people use javascript:null instead of void... but that's a problem. Chrome null works, in Firefox, it tries to load the page null. Glad you updated. Interesting bug. – Gavin Pickin Dec 28 '16 at 05:08
  • I found some other uses in a codebase like the javascript:null but with javascript:null() which is undefined, so that works. – Gavin Pickin Dec 28 '16 at 05:11
  • 1
    So basically it's like jquery's prevendDefault and return false? – Robert Rocha Oct 27 '17 at 14:22
18

Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.

So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.

Mohamad Shiralizadeh
  • 7,153
  • 5
  • 52
  • 78
17

To understand this concept one should first understand the void operator in JavaScript.

The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.

If you implement void as a function, it looks as follows:

function myVoid(expr) {
    return undefined;
}

This void operator has one important usage that is - discarding the result of an expression.

In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

javascript:void window.open("http://example.com/")
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gopal Yadav
  • 318
  • 2
  • 8
  • 2
    Thanks for clarifying exactly what the argument to 'void' is for! It wasn't clear in the other answers, only that "void takes an argument". – dbeachy1 Apr 13 '17 at 18:05
  • 1
    Good answer but one detail, the void implementation will be something like: `function myVoid(expr) { expr(); return undefined; }` You forgot add **expr();** – Juanma Menendez Nov 18 '18 at 04:30
  • 1
    @Juanma Menendez: not true. `expr` is already evaluated when `myVoid()` called (the *result* of that expression is passed as parameter) – Udo G Jan 06 '19 at 22:49
  • @UdoG I am curious, how do you know that men? can you please explain. – Juanma Menendez Jan 07 '19 at 03:07
  • @JuanmaMenendez: *expressions* in functions parameters are always evaluated before calling the function itself. Sorry, I have no document at hand that makes that clear but try yourself: `function() { alert("foo"); }` is a valid *expression*. `void(function() { alert("foo"); })`returns `undefined` and does **not** show the alert, whereas `myVoid(function() { alert("foo"); })` does (in your version, not the one of *Gopal Yadav*). – Udo G Jan 07 '19 at 08:08
15

The void operator evaluates the given expression and then returns undefined. It avoids refreshing the page.

katalin_2003
  • 701
  • 1
  • 13
  • 27
Abhay Singh
  • 1,302
  • 1
  • 21
  • 33
12

A link must have an href target to be specified to enable it to be a usable display object.

Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:

<a href="javascript:var el = document.getElementById('foo');">Get element</a>

Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.

So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.

The typical answer is to do something like this:

<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>

This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.

Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.

<a name="middleOfPage"></a>

You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:

<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>

There will be many times where you do not want that link jumping around, so you can do two things:

<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>

Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.

The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:

<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>

This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.

void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).

The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.

Aryan Beezadhur
  • 2,647
  • 1
  • 12
  • 31
1

From what I've seen, the void operator has 3 common uses in JavaScript. The one that you're referring to, <a href="javascript:void(0)"> is a common trick to make an <a> tag a no-op. Some browsers treat <a> tags differently based on whether they have a href , so this is a way to create a link with a href that does nothing.

The void operator is a unary operator that takes an argument and returns undefined. So var x = void 42; means x === undefined. This is useful because, outside of strict mode, undefined is actually a valid variable name. So some JavaScript developers use void 0 instead of undefined. In theory, you could also do <a href="javascript:undefined"> and it would so the same thing as void(0).

vkarpov15
  • 2,465
  • 18
  • 17