Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Created 25.09.2008 17:54
Viewed 2.37M times
4211 votes

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {
    alert("myJsFunc");
}
<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>

or

function myJsFunc() {
    alert("myJsFunc");
}
 <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

0
Answers 50
3
2213

I use javascript:void(0).

Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() {
    //Some code
    return false;
}

But then they forget to use return doSomething() in the onclick and just use doSomething().

A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.

A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:

onclick="someFunc.call(this)"

OR

onclick="someFunc.apply(this, arguments)"

Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.

So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:

Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

OR

Use href="javascript:void(0)"

The second is clearly much easier to communicate.

26.09.2008 08:03
Comments
Fast-forward to 2013: javascript:void(0) violates Content Security Policy on CSP-enabled HTTPS pages. One option would be then to use href='#' and event.preventDefault() in the handler, but I don't like this much. Perhaps you can establish a convention to use href='#void' and make sure no element on the page has id="void". That way, clicking a link to non-existing anchor will not scroll the page. by jakub.g, 01.10.2013 09:21
You can use "#" and then bind a click event to all links with "#" as the href. This would be done in jQuery with: $('a[href="#"]').click(function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; }); by Nathan, 14.02.2014 04:58
#void would add an entry to the browser history nonetheless. Another way would be to use the URL of a resource that returns HTTP status 204 (and still use preventDefault - the 204 is just a fallback). by CherryDT, 15.02.2021 22:35
0
1353

Neither.

If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.

If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.

I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.

Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).

25.09.2008 18:09
1
785

Doing <a href="#" onclick="myJsFunc();">Link</a> or <a href="javascript:void(0)" onclick="myJsFunc();">Link</a> or whatever else that contains an onclick attribute - was okay back five years ago, though now it can be a bad practice. Here's why:

  1. It promotes the practice of obtrusive JavaScript - which has turned out to be difficult to maintain and difficult to scale. More on this in Unobtrusive JavaScript.

  2. You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.

  3. There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.

The unobtrusive JavaScript way

Just don't have a href attribute at all! Any good CSS reset would take care of the missing default cursor style, so that is a non-issue. Then attach your JavaScript functionality using graceful and unobtrusive best practices - which are more maintainable as your JavaScript logic stays in JavaScript, instead of in your markup - which is essential when you start developing large scale JavaScript applications which require your logic to be split up into blackboxed components and templates. More on this in Large-scale JavaScript Application Architecture

Simple code example

// Cancel click event
$('.cancel-action').click(function(){
    alert('Cancel action occurs!');
});

// Hover shim for Internet Explorer 6 and Internet Explorer 7.
$(document.body).on('hover','a',function(){
    $(this).toggleClass('hover');
});
a { cursor: pointer; color: blue; }
a:hover,a.hover { text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cancel-action">Cancel this action</a>

A blackboxed Backbone.js example

For a scalable, blackboxed, Backbone.js component example - see this working jsfiddle example here. Notice how we utilize unobtrusive JavaScript practices, and in a tiny amount of code have a component that can be repeated across the page multiple times without side-effects or conflicts between the different component instances. Amazing!

Notes

  • Omitting the href attribute on the a element will cause the element to not be accessible using tab key navigation. If you wish for those elements to be accessible via the tab key, you can set the tabindex attribute, or use button elements instead. You can easily style button elements to look like normal links as mentioned in Tracker1's answer.

  • Omitting the href attribute on the a element will cause Internet Explorer 6 and Internet Explorer 7 to not take on the a:hover styling, which is why we have added a simple JavaScript shim to accomplish this via a.hover instead. Which is perfectly okay, as if you don't have a href attribute and no graceful degradation then your link won't work anyway - and you'll have bigger issues to worry about.

  • If you want your action to still work with JavaScript disabled, then using an a element with a href attribute that goes to some URL that will perform the action manually instead of via an Ajax request or whatever should be the way to go. If you are doing this, then you want to ensure you do an event.preventDefault() on your click call to make sure when the button is clicked it does not follow the link. This option is called graceful degradation.

25.02.2012 02:08
Comments
I use an actual hash not just # to open a lightbox. I have specifically made code that also open the lightbox when the url is assessed with that hash and manually add history events to the browser with the changed hash on the url. I consider this actually good practice and something expected that needed extra work on my part. However, my code just came in conflict with some 3rd party smooth scroll code that fucked up my event entirely. I am unsure if I just blame their code or if this approach is not so great after all. Again my case the #hash is actually not just to keep the style ... by redanimalwar, 07.02.2021 09:35
7
340

'#' will take the user back to the top of the page, so I usually go with void(0).

javascript:; also behaves like javascript:void(0);

25.09.2008 17:55
Comments
The way to avoid that is to return false in the onclick event handler. by Guvante, 25.09.2008 21:22
Returning false in the event handler doesn't avoid that if JavaScript the JS doesn't run successfully. by Quentin, 26.09.2008 08:10
using "#someNonExistantAnchorName" works well because it has nowhere to jump to. by scunliffe, 27.09.2008 02:46
If you have a base href, then # or #something will take you to that anchor on the base href page, instead of on the current page. by Abhi Beckert, 28.03.2012 06:39
Any use of # or void(0) is bad practice and shouldn't be encouraged. by user692942, 18.07.2013 12:06
The shebang (#!) does the trick but it's definitely bad practice. by Neel, 17.04.2014 00:23
@Neel, any anchor that doesn't actually exist in the document (e.g. #_) does the same trick, with the same drawbacks. by Ilya Streltsyn, 22.09.2014 09:18
Show remaining 2 comments
1
293

I would honestly suggest neither. I would use a stylized <button></button> for that behavior.

button.link {
  display: inline-block;
  position: relative;
  background-color: transparent;
  cursor: pointer;
  border: 0;
  padding: 0;
  color: #00f;
  text-decoration: underline;
  font: inherit;
}
<p>A button that looks like a <button type="button" class="link">link</button>.</p>

This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.


If you MUST use an A element, use javascript:void(0); for reasons already mentioned.

  • Will always intercept in case your onclick event fails.
  • Will not have errant load calls happen, or trigger other events based on a hash change
  • The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.

NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.

15.12.2011 18:41
Comments
This answer should be up top. If you are having this dilemma, chances are you are actually in need of a button. And IE9 is quickly losing market shares, fortunately, and the 1px active effect should not prevent us to use semantic markup. <a> is a link, it's meant to send you somewhere, for actions we have <button>'s. by mjsarfatti, 14.03.2016 15:00
2
144

The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.

<a href="#" onclick="myJsFunc(); return false;">Link</a>

If you use Angular2, this way works:

<a [routerLink]="" (click)="passTheSalt()">Click me</a>.

See here https://stackoverflow.com/a/45465728/2803344

25.09.2008 17:56
Comments
So in user agents with JavaScript enabled and the function supported this run a JavaScript function, falling back (for user agents where the JS fails for whatever reason) to a link to the top of the page? This is rarely a sensible fallback. by Quentin, 26.09.2008 08:09
"ideally with a real link to follow in case the user has JavaScript disabled", it should be going to a useful page not #, even if it's just an explanation that the site needs JS to work. as for failing, I would expect the developer to use proper browser feature detection, etc before deploying. by Zach, 26.09.2008 15:41
4
106

Neither if you ask me;

If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.

Example:

function callFunction() { console.log("function called"); }
.jsAction {
    cursor: pointer;
    color: #00f;
    text-decoration: underline;
}
<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>

25.09.2008 18:59
Comments
This approach restricts the 'link' to a mouse only operation. An anchor can be visited via the keyboard and its 'onclick' event is fired when the enter key is pressed. by AnthonyWJones, 26.09.2008 07:09
Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility. by Hosam Aly, 28.02.2009 19:21
<span>s are not meant to do anything. <A>nchors and <buttons> are used for that! by redShadow, 14.12.2011 23:15
Using buttons is a better choice here while using a span is not. by apnerve, 28.12.2012 08:33
0
101

Ideally you'd do this:

<a href="javascriptlessDestination.html" onclick="myJSFunc(); return false;">Link text</a>

Or, even better, you'd have the default action link in the HTML, and you'd add the onclick event to the element unobtrusively via JavaScript after the DOM renders, thus ensuring that if JavaScript is not present/utilized you don't have useless event handlers riddling your code and potentially obfuscating (or at least distracting from) your actual content.

25.09.2008 18:35
1
76

Using just # makes some funny movements, so I would recommend to use #self if you would like to save on typing efforts of JavaScript bla, bla,.

24.09.2011 01:55
Comments
For reference, #self doesn't appear to be special. Any fragment identifier that doesn't match the name or id of any element in the document (and isn't blank or "top") should have the same effect. by cHao, 17.05.2013 16:16
0
70

I use the following

<a href="javascript:;" onclick="myJsFunc();">Link</a>

instead

<a href="javascript:void(0);" onclick="myJsFunc();">Link</a>
17.04.2009 06:49
0
54

I agree with suggestions elsewhere stating that you should use regular URL in href attribute, then call some JavaScript function in onclick. The flaw is, that they automaticaly add return false after the call.

The problem with this approach is, that if the function will not work or if there will be any problem, the link will become unclickable. Onclick event will always return false, so the normal URL will not be called.

There's very simple solution. Let function return true if it works correctly. Then use the returned value to determine if the click should be cancelled or not:

JavaScript

function doSomething() {
    alert( 'you clicked on the link' );
    return true;
}

HTML

<a href="path/to/some/url" onclick="return !doSomething();">link text</a>

Note, that I negate the result of the doSomething() function. If it works, it will return true, so it will be negated (false) and the path/to/some/URL will not be called. If the function will return false (for example, the browser doesn't support something used within the function or anything else goes wrong), it is negated to true and the path/to/some/URL is called.

27.09.2008 10:58
0
54

I recommend using a <button> element instead, especially if the control is supposed to produce a change in the data. (Something like a POST.)

It's even better if you inject the elements unobtrusively, a type of progressive enhancement. (See this comment.)

16.10.2008 17:46
1
51

# is better than javascript:anything, but the following is even better:

HTML:

<a href="/gracefully/degrading/url/with/same/functionality.ext" class="some-selector">For great justice</a>

JavaScript:

$(function() {
    $(".some-selector").click(myJsFunc);
});

You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.

23.11.2009 20:38
Comments
@Muhd: Return should activate click on links… by Ry-, 10.04.2014 23:47
0
41

Unless you're writing out the link using JavaScript (so that you know it's enabled in the browser), you should ideally be providing a proper link for people who are browsing with JavaScript disabled and then prevent the default action of the link in your onclick event handler. This way those with JavaScript enabled will run the function and those with JavaScript disabled will jump to an appropriate page (or location within the same page) rather than just clicking on the link and having nothing happen.

25.09.2008 18:02
0
37

Definitely hash (#) is better because in JavaScript it is a pseudoscheme:

  1. pollutes history
  2. instantiates new copy of engine
  3. runs in global scope and doesn't respect event system.

Of course "#" with an onclick handler which prevents default action is [much] better. Moreover, a link that has the sole purpose to run JavaScript is not really "a link" unless you are sending user to some sensible anchor on the page (just # will send to top) when something goes wrong. You can simply simulate look and feel of link with stylesheet and forget about href at all.

In addition, regarding cowgod's suggestion, particularly this: ...href="javascript_required.html" onclick="... This is good approach, but it doesn't distinguish between "JavaScript disabled" and "onclick fails" scenarios.

07.11.2009 02:26
6
22

It would be better to use jQuery,

$(document).ready(function() {
    $("a").css("cursor", "pointer");
});

and omit both href="#" and href="javascript:void(0)".

The anchor tag markup will be like

<a onclick="hello()">Hello</a>

Simple enough!

23.10.2008 09:55
Comments
This is what I was going to say. If a link has a fallback url that makes sense, use that. Otherwise, just omit the href or use something more semantically appropriate than an <a>. If the only reason everyone is advocating including the href is to get the finger on hover, a simple "a { cursor: pointer; }" will do the trick. by Matt Kantor, 22.07.2009 13:40
May I say this is the option that SO decided to go with. Check the "flag" links, for instance. by mtyaka, 24.11.2009 10:19
That gives terrible accessibility. Try it in SO: you can't flag a post without using the mouse. The "link" and "edit" links are accessible by tabbing, but "flag" isn't. by Nicolás, 07.07.2010 03:51
I agree with this option. If the anchor has no purpose other than JavaScript, it shouldn't have a href. @Fatih: Using jQuery means that if JavaScript is disabled, the link will NOT have a pointer. by Scott Rippey, 17.06.2011 19:32
If you are going to go this route, why not bind the click using jQuery as well? Part of the great thing about using jQuery is the ability to seperate your javascript from your markup. by Muhd, 14.12.2011 22:39
Better to add a js class to the body, and Let CSS handle the CSS. body.js a{cursor: pointer;} by AndFisher, 18.01.2017 14:45
Show remaining 1 comments
0
26

I choose use javascript:void(0), because use this could prevent right click to open the content menu. But javascript:; is shorter and does the same thing.

26.07.2011 11:35
0
30

I usually go for

<a href="javascript:;" onclick="yourFunction()">Link description</a>

It's shorter than javascript:void(0) and does the same.

13.08.2015 01:01
1
27

I would use:

<a href="#" onclick="myJsFunc();return false;">Link</a>

Reasons:

  1. This makes the href simple, search engines need it. If you use anything else ( such as a string), it may cause a 404 not found error.
  2. When mouse hovers over the link, it doesn't show that it is a script.
  3. By using return false;, the page doesn't jump to the top or break the back button.
16.12.2011 00:09
Comments
i dont agree with "1." cause it gives error when u put ur script link when scripts are not allowed. so that kind of links should be added with the js code. that way people can avoid those links while script is not allowed and see no errors at all. by Berker Yüceer, 30.12.2011 11:32
0
25

So, when you are doing some JavaScript things with an <a /> tag and if you put href="#" as well, you can add return false at the end of the event (in case of inline event binding) like:

<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>

Or you can change the href attribute with JavaScript like:

<a href="javascript://" onclick="myJsFunc();">Run JavaScript Code</a>

or

<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a> tag.

You can simply use a <button /> instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.


So, there is one benefit to use <a href="#">. You get the cursor pointer by default on that element when you do a href="#". For that, I think you can use CSS for this like cursor:pointer; which solves this problem also.

And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault() to achieve this if you are using <a> tag, but if you are not using a <a> tag for this, there you get an advantage, you don't need to do this.

So, if you see, it's better not to use a tag for this kind of stuff.

13.02.2014 03:34
3
23

Don't use links for the sole purpose of running JavaScript.

The use of href="#" scrolls the page to the top; the use of void(0) creates navigational problems within the browser.

Instead, use an element other than a link:

<span onclick="myJsFunc()" class="funcActuator">myJsFunc</span>

And style it with CSS:

.funcActuator { 
  cursor: default;
}

.funcActuator:hover { 
  color: #900;
}
26.01.2016 19:54
Comments
Use a button, not a span. Buttons naturally fall in the focus order so can be accessed without a mouse / trackpad / etc. by Quentin, 15.06.2016 12:12
Adding ton Quentin's comment: as currently written, keyboard users won't reach the span element because it is a non-focusable element. That's why you need a button. by Tsundoku, 25.07.2017 13:09
You can make it focusable by adding tabindex="0" to the span. That said, using button is better because it gives you the desired functionality for free. To make it accessible using a span you not only need to attach a click handler, but a keyboard event handler that looks for presses of space bar or enter key and then fires the normal click handler. You would also want to change the second CSS selector to .funcActuator:hover, .funcActuator:focus so the fact that the element has focus is apparent. by Useless Code, 22.11.2017 11:45
2
19

If you happen to be using AngularJS, you can use the following:

<a href="">Do some fancy JavaScript</a>

Which will not do anything.

In addition

  • It will not take you to the top of the page, as with (#)
    • Therefore, you don't need to explicitly return false with JavaScript
  • It is short an concise
25.07.2013 22:31
Comments
But this would cause the page to reload, and since we're always using javascript to modify the page, this is unacceptable. by Henry Hu, 30.07.2013 00:16
@HenryHu I figured out that the reason it did not reload was because of AngularJS. See my updated answer. by whirlwin, 30.07.2013 10:46
0
19

Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript.

Example... Let's say you have the following search link:

<a href="search.php" id="searchLink">Search</a>

You can always do the following:

var link = document.getElementById('searchLink');

link.onclick = function() {
    try {
        // Do Stuff Here        
    } finally {
        return false;
    }
};

That way, people with JavaScript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.

16.10.2008 18:00
1
16

I believe you are presenting a false dichotomy. These are not the only two options.

I agree with Mr. D4V360 who suggested that, even though you are using the anchor tag, you do not truly have an anchor here. All you have is a special section of a document that should behave slightly different. A <span> tag is far more appropriate.

25.09.2008 21:20
Comments
Also if you were to replace an a with a span, you'll need to remember to make it focusable via keyboard. by AndFisher, 18.01.2017 14:42
1
16

Depending on what you want to accomplish, you could forget the onclick and just use the href:

<a href="javascript:myJsFunc()">Link Text</a>

It gets around the need to return false. I don't like the # option because, as mentioned, it will take the user to the top of the page. If you have somewhere else to send the user if they don't have JavaScript enabled (which is rare where I work, but a very good idea), then Steve's proposed method works great.

<a href="javascriptlessDestination.html" onclick="myJSFunc(); return false;">Link text</a>

Lastly, you can use javascript:void(0) if you do not want anyone to go anywhere and if you don't want to call a JavaScript function. It works great if you have an image you want a mouseover event to happen with, but there's not anything for the user to click on.

25.09.2008 21:02
Comments
The only downside with this (from memory, I may be wrong) is that IE doesn't consider an A to be an A if you don't have a href inside it. (So CSS rules won't work) by Benjol, 26.09.2008 12:01
1
16

I tried both in google chrome with the developer tools, and the id="#" took 0.32 seconds. While the javascript:void(0) method took only 0.18 seconds. So in google chrome, javascript:void(0) works better and faster.

29.10.2016 19:10
Comments
Actually they don't do the same. # makes you jump to top of the page. by Jochen Schultz, 21.09.2017 10:58
0
17

I personally use them in combination. For example:

HTML

<a href="#">Link</a>

with little bit of jQuery

$('a[href="#"]').attr('href','javascript:void(0);');

or

$('a[href="#"]').click(function(e) {
   e.preventDefault();
});

But I'm using that just for preventing the page jumping to the top when the user clicks on an empty anchor. I'm rarely using onClick and other on events directly in HTML.

My suggestion would be to use <span> element with the class attribute instead of an anchor. For example:

<span class="link">Link</span>

Then assign the function to .link with a script wrapped in the body and just before the </body> tag or in an external JavaScript document.

<script>
    (function($) {
        $('.link').click(function() {
            // do something
        });
    })(jQuery);
</script>

*Note: For dynamically created elements, use:

$('.link').on('click', function() {
    // do something
});

And for dynamically created elements which are created with dynamically created elements, use:

$(document).on('click','.link', function() {
    // do something
});

Then you can style the span element to look like an anchor with a little CSS:

.link {
    color: #0000ee;
    text-decoration: underline;
    cursor: pointer;
}
.link:active {
    color: red;
}

Here's a jsFiddle example of above aforementioned.

26.04.2014 18:37
4
13

It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use "#" with a "return false;" to prevent the default action (scroll to top of the page) as others have mentioned.

Googling for "javascript:void(0)" provides a lot of information on this topic. Some of them, like this one mention reasons to NOT use void(0).

25.09.2008 18:40
Comments
The blog entry does not cite the reference as to why javascript:void(0) should be avoided. by AnthonyWJones, 26.09.2008 07:20
The link is (effectively) broken now. by Peter Mortensen, 31.05.2011 08:06
Not good solution for accessibility: dequeuniversity.com/rules/axe/3.0/href-no-hash by Hrvoje Golcic, 26.11.2019 15:13
javascript:void(0); is also not good if you want to use a strict Content Security Policy that disables inline JavaScript. by Scott Schupbach, 07.04.2020 18:59
0
16

When I've got several faux-links, I prefer to give them a class of 'no-link'.

Then in jQuery, I add the following code:

$(function(){
   $('.no-link').click(function(e){
       e.preventDefault();
   });
});

And for the HTML, the link is simply

<a href="/" class="no-link">Faux-Link</a>

I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).

<a href="javascript:void(0)" class="no-link">Faux-Link</a>

Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.

25.06.2012 19:34
2
7

If you are using an <a> element, just use this:

<a href="javascript:myJSFunc();" />myLink</a>

Personally I'd attach an event handler with JavaScript later on instead (using attachEvent or addEventListener or maybe <put your favorite JavaScript framework here > also).

26.09.2008 11:44
Comments
Can someone explain the reason why this answer has so many downvotes? by Timo Huovinen, 16.05.2012 19:36
This answer has man downvotes because (as noted in the other response) putting javascript in the actual tag is considered very bad practice. Click handlers should never be in the HTML itself. The top answer best explains this in detail. by David Granado, 15.03.2013 14:31
1
13

I'm basically paraphrasing from this practical article using progressive enhancement. The short answer is that you never use javascript:void(0); or # unless your user interface has already inferred that JavaScript is enabled, in which case you should use javascript:void(0);. Also, do not use span as links, since that is semantically false to begin with.

Using SEO friendly URL routes in your application, such as /Home/Action/Parameters is a good practice as well. If you have a link to a page that works without JavaScript first, you can enhance the experience afterward. Use a real link to a working page, then add an onlick event to enhance the presentation.

Here is a sample. Home/ChangePicture is a working link to a form on a page complete with user interface and standard HTML submit buttons, but it looks nicer injected into a modal dialog with jQueryUI buttons. Either way works, depending on the browser, which satisfies mobile first development.

<p><a href="Home/ChangePicture" onclick="return ChangePicture_onClick();" title="Change Picture">Change Picture</a></p>

<script type="text/javascript">
    function ChangePicture_onClick() {
        $.get('Home/ChangePicture',
              function (htmlResult) {
                  $("#ModalViewDiv").remove(); //Prevent duplicate dialogs
                  $("#modalContainer").append(htmlResult);
                  $("#ModalViewDiv").dialog({
                      width: 400,
                      modal: true,
                      buttons: {
                          "Upload": function () {
                              if(!ValidateUpload()) return false;
                              $("#ModalViewDiv").find("form").submit();
                          },
                          Cancel: function () { $(this).dialog("close"); }
                      },
                      close: function () { }
                  });
              }
        );
        return false;
    }
</script>
14.12.2011 22:09
Comments
In term of SEO I would prefer this way. Using as many friendly URL shall definitely improve page value factor. by Chetabahana, 21.04.2015 22:18
0
12

On a modern website the use of href should be avoided if the element is only doing JavaScript functionality (not a real link).

Why? The presence of this element tells the browser that this is a link with a destination. With that, the browser will show the Open In New Tab / Window function (also triggered when you use shift+click). Doing so will result in opening the same page without the desired function triggered (resulting in user frustration).

In regards to IE: As of IE8, element styling (including hover) works if the doctype is set. Other versions of IE are not really to worry about anymore.

Only Drawback: Removing HREF removes the tabindex. To overcome this, you can use a button that's styled as a link or add a tabindex attribute using JS.

26.03.2017 23:27
0
11

You can also write a hint in an anchor like this:

<a href="javascript:void('open popup image')" onclick="return f()">...</a>

so the user will know what this link does.

28.02.2009 17:06
5
6

If you use a link as a way to just execute some JavaScript code (instead of using a span like D4V360 greatly suggested), just do:

<a href="javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B">test</a>

If you're using a link with onclick for navigation, don't use href="#" as the fallback when JavaScript is off. It's usually very annoying when the user clicks on the link. Instead, provide the same link the onclick handler would provide if possible. If you can't do that, skip the onclick and just use a JavaScript URI in the href.

25.09.2008 21:38
Comments
This would give an error if JS was off instead of seemingly doing nothing or just go to the top of the page by mplungjan, 14.01.2012 19:24
@mplungjan If JS is off, clicking it will do nothing, which makes sense if there's no non-js alternative representation/action of what the JS is doing. Having the href be "#" or some URI isn't any more useful, in the case I was describing. by Shadow2531, 15.01.2012 06:07
So have href="jsdisabled.html" instead by mplungjan, 15.01.2012 10:28
@mplungjan You could. But, that navigates away from the page. by Shadow2531, 16.01.2012 05:52
@mplungjan Understood. You could do that. No argument there. I'd personally just have a "this page requires JS" message for the page that disappears when JS is on though. by Shadow2531, 17.01.2012 04:09
0
11

I'd say the best way is to make an href anchor to an ID you'd never use, like #Do1Not2Use3This4Id5 or a similar ID, that you are 100% sure no one will use and won't offend people.

  1. Javascript:void(0) is a bad idea and violates Content Security Policy on CSP-enabled HTTPS pages https://developer.mozilla.org/en/docs/Security/CSP (thanks to @jakub.g)
  2. Using just # will have the user jump back to the top when pressed
  3. Won't ruin the page if JavaScript isn't enabled (unless you have JavaScript detecting code
  4. If JavaScript is enabled you can disable the default event
  5. You have to use href unless you know how to prevent your browser from selecting some text, (don't know if using 4 will remove the thing that stops the browser from selecting text)

Basically no one mentioned 5 in this article which I think is important as your site comes off as unprofessional if it suddenly starts selecting things around the link.

20.03.2014 10:55
0
10

I use href="#" for links that I want a dummy behaviour for. Then I use this code:

$(document).ready(function() {
    $("a[href='#']").click(function(event) {
        event.preventDefault();
    });
});

Meaning if the href equals to a hash (*="#") it prevents the default link behaviour, thus still allowing you to write functionality for it, and it doesn't affect anchor clicks.

07.03.2014 14:28
3
8

You could use the href and remove all links that have only hashes:

HTML:

<a href="#" onclick="run_foo()"> foo </a>

JS:

$(document).ready(function(){         // on DOM ready or some other event

   $('a[href=#]').attr('href','');    // set all reference handles to blank strings
                                      //  for anchors that have only hashes

});
22.08.2012 16:08
Comments
This is bad, particularly in IE (up to version 10, not sure about 11). Clicking a link with an empty href results in an unnecessary (and probably unwanted) request being fired, and in IE, it attempts to open Windows Explorer. by squidbe, 03.03.2014 22:12
@squidbe: This was an old answer but I think that depends on how your JS is written. If you didn't want that to fire, I think you would onclick="return run_foo()" and have run_foo return false or just add a return false line after the function is called. The point of this answer was that you could remove href tags when JS is enabled. The ideal solution would be to populate the href with a fail-safe link most likely to a server-side rendered page href="render/full_page.script?arg=value" onclick="loadAJAXContent.call(this); return false" by vol7ron, 02.06.2014 16:13
You are correct about the fail-safe solution. My point was that the href attribute value is not intended to ever be an empty string, and setting it to empty can cause unwanted side effects. Even when you return false, if there are errors in your script, the undesired request and undesired Windows behavior still occur. If the option is between leaving the hash in the href and removing it via script, I think it's better to leave it. by squidbe, 02.06.2014 18:03
0
9

There is one more important thing to remember here. Section 508 compliance. Because of it, I feel it's necessary to point out that you need the anchor tag for screen readers such as JAWS to be able to focus it through tabbing. So the solution "just use JavaScript and forget the anchor to begin with" is not an option for some of this. Firing the JavaScript inside the href is only necessary if you can't afford for the screen to jump back up to the top. You can use a settimeout for 0 seconds and have JavaScript fire to where you need focus but even the apage will jump to the top and then back.

27.12.2010 15:17
0
9

I see a lot of answers by people who want to keep using # values for href, hence, here is an answer hopefully satisfying both camps:

A) I'm happy to have javascript:void(0) as my href value:

<a href="javascript:void(0)" onclick="someFunc.call(this)">Link Text</a>

B) I am using jQuery, and want # as my href value:

<a href="#" onclick="someFunc.call(this)">Link Text</a>

<script type="text/javascript">
    /* Stop page jumping when javascript links are clicked.
       Only select links where the href value is a #. */
    $('a[href="#"]').live("click", function(e) {
         return false; // prevent default click action from happening!
         e.preventDefault(); // same thing as above
    });
</script>

Note, if you know links won't be created dynamically, use the click function instead:

$('a[href="#"]').click(function(e) {

16.03.2012 02:16
0
8

What I understand from your words is that you want to create a link just to run JavaScript code.

Then you should consider that there are people who blocks JavaScript out there in their browsers.

So if you are really going to use that link only for running a JavaScript function then you should add it dynamically so it won't be even seen if the users didn't enable their JavaScript in the browser and you are using that link just to trigger a JavaScript function which makes no sense to use a link like that when JavaScript is disabled in the browser.

For that reason neither of them is good when JavaScript is disabled.

Aand if JavaScript is enabled and you only want to use that link to invoke a JavaScript function then

<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>

is far better way than using

<a href="#" onclick="myJsFunc();">Link</a>

because href="#" is going to cause the page to do actions that are not needed.

Also, another reason why <a href="javascript:void(0)" onclick="myJsFunc();">Link</a> is better than <a href="#" onclick="myJsFunc();">Link</a> is that JavaScript is used as the default scripting language for most of the browsers. As an example Internet Explorer, uses an onclick attribute to define the type of scripting language that would be used. Unless another good scripting language pops up, JavaScript will be used by Internet Explorer as the default too, but if another scripting language used javascript:, it would let Internet Explorer to understand which scripting language is being used.

Considering this, I would prefer using and exercising on

<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>

enough to make it a habit and to be more user friendly please add that kind of links within the JavaScript code:

$(document).ready(function(){
    $(".blabla").append('<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>')
});
15.12.2011 09:21
0
9

The most simple and used by everyone mostly is javascript:void(0) You can use it instead of using # to stop tag redirect to header section.

<a href="javascript:void(0)" onclick="testFunction();">Click To check Function</a>

function testFunction() {
    alert("hello world");
}
14.06.2019 11:37
1
8

Just to pick up the point some of the other have mentioned.

It's much better to bind the event 'onload'a or $('document').ready{}; then to put JavaScript directly into the click event.

In the case that JavaScript isn't available, I would use a href to the current URL, and perhaps an anchor to the position of the link. The page is still be usable for the people without JavaScript those who have won't notice any difference.

As I have it to hand, here is some jQuery which might help:

var [functionName] = function() {
   // do something
};

jQuery("[link id or other selector]").bind("click", [functionName]);
23.10.2008 14:22
Comments
LowPro is really nice for unobtrusive JS if you have a lot of complex behaviors. by Matt Kantor, 22.07.2009 13:43
0
9

Don't lose sight of the fact that your URL may be necessary -- onclick is fired before the reference is followed, so sometimes you will need to process something clientside before navigating off the page.

25.09.2008 17:57
4
8

Why not using this? This doesn't scroll page up.

<span role="button" onclick="myJsFunc();">Run JavaScript Code</span>
18.11.2014 15:42
Comments
This actually seems like a very good solution, thanks. I've replaced href="#" with role="button" everywhere and then stuck *[role="button"] { cursor:pointer; } in the CSS and that seems to work very well without the need for unnecessary JS :) by Alex Yorke, 29.12.2014 20:20
As others have said, this cannot be activated using the keyboard. by Martin, 14.03.2017 14:18
Yeah, when pressing TAB key one cannot navigate to it. Using tabindex="0" might make it better but I'm not sure it that's appropriate solution by Hrvoje Golcic, 26.11.2019 15:15
5 years after the answer I also consider the a11y features:) by AlxGol, 27.11.2019 07:43
0
7

Ideally you should have a real URL as fallback for non-JavaScript users.

If this doesn't make sense, use # as the href attribute. I don't like using the onclick attribute since it embeds JavaScript directly in the HTML. A better idea would be to use an external JS file and then add the event handler to that link. You can then prevent the default event so that the URL doesn't change to append the # after the user clicks it.

25.09.2008 18:50
2
6

You should not use inline onclick="something();" in your HTML to not polluate it with meaningless code; all click bindings must be set in Javascript files (*.js).

Set binding like this : $('#myAnchor').click(function(){... **return false**;}); or $('#myAnchor').bind('click', function(){... **return false**;});

Then you have a clean HTML file easy to load (and seo friendly) without thousands of href="javascript:void(0);" and just href="#"

08.02.2013 14:15
Comments
this doesn't answer the question of what to do with href. if you don't have an href attribute on an a tag, it won't appear as a clickable link. by user428517, 12.08.2013 14:17
But what if there is a list of elements and I want add link to remove some element from it by string ID? by ryabenko-pro, 22.10.2013 12:55
2
3

Here is one more option for completeness sake, that prevents the link from doing anything even if JavaScript is disabled, and it's short :)

<a href="#void" onclick="myJsFunc()">Run JavaScript function</a>

If the id is not present on the page, then the link will do nothing.

Generally, I agree with the Aaron Wagner's answer, the JavaScript link should be injected with JavaScript code into the document.

15.03.2012 09:43
Comments
In HTML5, most of the restrictions on IDs are lifted, so they can start with a number. The only restrictions now are that they must be unique and cannot contain spaces. See whatwg.org/specs/web-apps/current-work/multipage/…. Also, your solution modifies the URL and inserts a history entry, polluting the back button with useless states. by Andy E, 16.05.2012 13:07
@AndyE yep, your right, I wasn't aware that id's could start with numbers, also this solution was never meant to be any good or recommended, I added it for "completeness sake" on the number of ways to do it. by Timo Huovinen, 16.05.2012 13:16
0
6

I strongly prefer to keep my JavaScript out of my HTML markup as much as possible. If I'm using <a> as click event handlers then I'd recommend using <a class="trigger" href="#">Click me!</a>.

$('.trigger').click(function (e) {
    e.preventDefault();
    // Do stuff...
});

It's very important to note that many developers out there believe that using anchor tags for click-event handlers isn't good. They'd prefer you to use a <span> or <div> with some CSS that adds cursor: pointer; to it. This is a matter if much debate.

14.12.2011 21:06
0
7

Edited on 2019 January

In HTML5, using an a element without an href attribute is valid. It is considered to be a "placeholder hyperlink"

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

Example:

<a>previous</a>

If after that you want to do otherwise :

1 - If your link doesn't go anywhere, don't use an <a> element. Use a <span> or something else appropriate and add CSS :hover to style it as you wish.

2 - Use the javascript:void(0) OR javascript:undefined OR javascript:; if you want to be raw, precise and fast.

02.01.2019 15:45
0
7

In total agreement with the overall sentiment, use void(0) when you need it, and use a valid URL when you need it.

Using URL rewriting you can make URLs that not only do what you want to do with JavaScript disabled, but also tell you exactly what its going to do.

<a href="./Readable/Text/URL/Pointing/To/Server-Side/Script" id="theLinkId">WhyClickHere</a>

On the server side, you just have to parse the URL and query string and do what you want. If you are clever, you can allow the server side script to respond to both Ajax and standard requests differently. Allowing you to have concise centralized code that handles all the links on your page.

URL rewriting tutorials

Pros

  • Shows up in status bar
  • Easily upgraded to Ajax via onclick handler in JavaScript
  • Practically comments itself
  • Keeps your directories from becoming littered with single use HTML files

Cons

  • Should still use event.preventDefault() in JavaScript
  • Fairly complex path handling and URL parsing on the server side.

I am sure there are tons more cons out there. Feel free to discuss them.

17.07.2010 22:46