4459

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>

3
  • 17
    Why use a link when you want a button? Then there is no issue with pseudo–protocols. Commented Jun 11, 2022 at 12:57
  • Neither. If you really must use a link, then use a span styled as a link. No href to bother about. And why void(0) when void 0 will do? Commented Apr 16, 2023 at 7:43
  • @RobG Because a link behaves differently. For example a link can be middle clicked to open in new tab and has other options in right-click menu... Commented Feb 20 at 9:51

56 Answers 56

1
2
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> 
Sign up to request clarification or add additional context in comments.

1 Comment

In term of SEO I would prefer this way. Using as many friendly URL shall definitely improve page value factor.
11

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.

Comments

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.

Comments

10

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.

Comments

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.

Comments

9

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.

Comments

9

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]); 

1 Comment

LowPro is really nice for unobtrusive JS if you have a lot of complex behaviors.
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"); } 

1 Comment

if use versión that require detect javascript and use function for dectect browser version you can instead using # ``` <a href="javascript:void(0)" onclick="testFunction();">Click to check </a> function testFunction() { alert("hello, world") } ```
8

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.

Comments

8

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

2 Comments

Can someone explain the reason why this answer has so many downvotes?
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.
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>') }); 

Comments

8

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

Comments

8

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

<span role="button" onclick="myJsFunc();">Run JavaScript Code</span> 

7 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 :)
As others have said, this cannot be activated using the keyboard.
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
5 years after the answer I also consider the a11y features:)
@HrvojeGolcic Please note the accessibility concerns when using tabindex.
|
8

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.

Comments

7

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.

5 Comments

This would give an error if JS was off instead of seemingly doing nothing or just go to the top of the page
@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.
So have href="jsdisabled.html" instead
@mplungjan You could. But, that navigates away from the page.
@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.
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.

Comments

7

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

3 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.
@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"
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.
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.

Comments

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="#"

2 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.
But what if there is a list of elements and I want add link to remove some element from it by string ID?
4

You can use javascript:void(0) here instead of using # to stop anchor tag redirect to header section.

function helloFunction() { alert("hello world"); } <a href="javascript:void(0)" onclick="helloFunction();">Call Hello Function</a> 

1 Comment

If one uses the '#' and does not wish the redirect, one simply needs to ensure that whatever onclick behavior being triggered by the event returns false as its final return value. This will prevent the navigation after the click event has finished bubbling. It can even be something sillly, like onclick="return console.log('I am a worthless link!')" (the console log evaluates to undefined, which yields a falsey value). void(0) is simply an old school syntax for getting a true undefined response.
4

There are actually four options here.

Using return false; allows you to keep the anchor version in cases where you want a safe "fallback" in browsers that have JavaScript disabled or it is not supported in the user agent (1-5% of user's now). You can use the anchor "#" sign, an empty string, or a special URL for the href should your script fail. Note that you must use an href so screen readers know it is a hyperlink. (Note: I am not going to get into arguments about removing the href attribute as that point is moot here. Without an href on an anchor means the anchor is no longer a hyperlink and just an html tag with a click event on it that is captured.)

<a href="" onclick="alert('hello world!');return false;">My Link</a> <a href="#" onclick="alert('hello world!');return false;">My Link</a> <a href="MyFallbackURL.html" onclick="alert('hello world!');return false;">My Link</a> 

Below is the more popular design today using javascript:void(0) inside the href attribute. If a browser doesn't support scripting it should post again back to its page again, as an empty string is returned for the href hyperlink path. Use this if you don't care who supports JavaScript.

<a href="javascript:void(0);" onclick="alert('hello world!');">My Link</a> 

Comments

2

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 on the page, the link will do nothing.

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

2 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.
@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.
1

Javascript: void(0); is void to null value [Not assigned], which means your browser is going to NULL click to DOM, and the window return to false.
• The '#' does not follow the DOM or Window in javascript. which that mean the '#' sign inside anchor href is a LINK. Link to the same current direction.

Comments

0

javascript:void(0) will deprecate in future, therefore you should use #.

Comments

0

Why not use:

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

Or am I missing a downfall with this method? I know its an old post but still people are looking for this.

Comments

-3

Why not just completely omit the href? Like so:

<a onclick="myfunction()">Link</a> 

1 Comment

This will cause the link to not be focusable so it creates a major accessibility barrier.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.