Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

When building a link that has the sole purpose to run JavaScript code, there are 2 ways to write the code. Which is better, in terms of functionality, page load speed, validation purposes, etc?

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

or

<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
share|improve this question
show 1 more comment

38 Answers

1 2

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

share|improve this answer
13  
The way to avoid that is to return false in the onclick event handler. – Guvante Sep 25 '08 at 21:22
5  
Returning false in the event handler doesn't avoid that if JavaScript the JS doesn't run successfully. – Quentin Sep 26 '08 at 8:10
10  
using "#someNonExistantAnchorName" works well because it has nowhere to jump to. – scunliffe Sep 27 '08 at 2:46
2  
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. – Abhi Beckert Mar 28 '12 at 6:39
show 1 more comment

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>
share|improve this answer
10  
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. – Quentin Sep 26 '08 at 8:09
11  
"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. – Zach Sep 26 '08 at 15:41
1  
My web apps are designed to degrade gracefully, so the link will still be a useful page. Unless your web app is a chat client or something that interactive, this should work if you put in the time to design with degradation in mind. – Zach Jul 13 '09 at 23:08
show 4 more comments

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.

share|improve this answer

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.

share|improve this answer
up vote 355 down vote
+50

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).

share|improve this answer
3  
+1 for definite "neither" – Alex Shesterov Mar 20 at 21:46

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.

share|improve this answer

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).

share|improve this answer
show 2 more comments

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.

share|improve this answer

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:

<style type="text/css">
    .jsAction {
        cursor: pointer;
        color: #00f;
        text-decoration: underline;
    }
</style>

<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>
share|improve this answer
84  
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. – AnthonyWJones Sep 26 '08 at 7:09
25  
Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility. – Hosam Aly Feb 28 '09 at 19:21
1  
Quite cumbersome. A link would have solved the problem too. – usr May 21 '10 at 15:08
9  
<span>s are not meant to do anything. <A>nchors and <buttons> are used for that! – redShadow Dec 14 '11 at 23:15
show 2 more comments

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.

share|improve this answer
3  
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) – Benjol Sep 26 '08 at 12:01

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 tag is far more appropriate.

share|improve this answer

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.

share|improve this answer
show 6 more comments

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.

share|improve this answer

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).

share|improve this answer
7  
Can someone explain the reason why this answer has so many downvotes? – Timo Huovinen May 16 '12 at 19:36
1  
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. – Just a guy Mar 15 at 14:31

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.

share|improve this answer
show 3 more comments

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.)

share|improve this answer
show 2 more comments

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.

share|improve this answer

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!

share|improve this answer
2  
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. – Matt Kantor Jul 22 '09 at 13:40
9  
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. – Nicolás Jul 7 '10 at 3:51
11  
why using jQuery instead of css a { cursor: pointer; } – Fatih Mar 23 '11 at 14:53
3  
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. – Scott Rippey Jun 17 '11 at 19:32
2  
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. – Muhd Dec 14 '11 at 22:39
show 1 more comment

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() {
};

jQuery("[link id or other selector]").bind("click", [functionName]);
share|improve this answer
show 1 more comment

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.

share|improve this answer

I use

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

instead of

<a href="javascript:void(0)" onclick="myJsFunc();">Link</a>
share|improve this answer
5  
"semantically faster"? wtf does that mean? ~_^ – Jonas Kölker Nov 27 '12 at 11:23
show 2 more comments

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.

share|improve this answer
1  
this is good stuff – Pacerier Sep 1 '11 at 16:35

# 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.

share|improve this answer
1  
+1 For the general idea, although you are losing keyboard functionality with this. – Muhd Dec 14 '11 at 22:46

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.

share|improve this answer

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.

share|improve this answer

I choose use javascript:void(0), because use this could prevent right click to open the content menu.

share|improve this answer

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,".

share|improve this answer
3  
WOW, thumbs up for this tip. Never knew that you could use the #self for named tags, and avoid the annoying browser behavior of jumping to top of page. Thank you. – alonso.torres Nov 25 '11 at 16:49
2  
This is a nice tip. Kind of makes me wonder why "#" is so popular. – Muhd Dec 14 '11 at 22:45

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.

share|improve this answer

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>
share|improve this answer

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>')
});
share|improve this answer
1 2

protected by Yi Jiang Nov 9 '11 at 15:49

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.