By 2cBGj7vsfp


2008-09-25 17:54:27 8 Comments

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>

30 comments

@treat your mods well 2008-10-16 17:46:51

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

@mateuscb 2011-10-17 18:45:05

I too think this is the best solution. If you have an element that is meant to perform an action, there is no reason for it be an link.

@kontur 2011-12-16 11:09:24

Were you to ask and your href would look like "#something" some of the other listed answers might serve, but: Without the href linking to anything sensible, there is no point in having a href, or even a link altogether. The suggested use of button might do, or use any other element but a link thank links nowhere.

@Ciro Santilli 郝海东冠状病六四事件法轮功 2014-09-19 12:42:21

Another advantage of this is that Bootstrap .btn makes buttons and links look exactly the same.

@Coll 2019-12-18 22:38:11

From a user perspective, button also doesn't introduce a # into the URL or show the a href as javascript:;

@Dev pokhariya 2019-06-14 11:37:31

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

@Javed Khan 2019-05-29 04:49:55

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>

@SchoolforDesign 2019-05-14 13:40:51

Javascript: void(0); is void to null value [Not assigned], which that mean your browser is going to NULL click to DOM, and window return to false.
• The '#' is 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.

@TomDK 2017-03-26 23:27:35

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.

@mdesdev 2014-04-26 18:37:30

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.

@Matt Goddard 2008-10-23 14:22:33

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

@Matt Kantor 2009-07-22 13:43:23

LowPro is really nice for unobtrusive JS if you have a lot of complex behaviors.

@L Y E S - C H I O U K H 2019-01-02 15:45:25

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.

@mmacaulay 2008-09-25 18:40:14

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

@AnthonyWJones 2008-09-26 07:20:27

The blog entry does not cite the reference as to why javascript:void(0) should be avoided.

@Peter Mortensen 2011-05-31 08:06:23

The link is (effectively) broken now.

@Hrvoje Golcic 2019-11-26 15:13:53

Not good solution for accessibility: dequeuniversity.com/rules/axe/3.0/href-no-hash

@Scott Schupbach 2020-04-07 18:59:49

javascript:void(0); is also not good if you want to use a strict Content Security Policy that disables inline JavaScript.

@user564706 2011-07-26 11:35:44

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.

@se_pavel 2009-04-17 06:49:34

I use the following

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

instead

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

@Boann 2012-07-29 04:18:04

I use javascript: (no semi-colon) because it looks tidiest in the status bar on hover.

@Ilya Streltsyn 2013-07-08 16:43:10

This code may cause bad surprises in older IE. At some point it used to break any animation effects with images, including rollovers and even animated gifs: groups.google.com/forum/#!topic/comp.lang.javascript/…

@Tracker1 2014-12-19 17:09:15

You can always do... javascript:void('Do foo') since void will return undefined regardless, it will give an indicator to the user what clicking will do. Where Do foo can be Delete record X or whatever you like.

@Tracker1 2011-12-15 18:41:57

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.

@Brennan Roberts 2012-07-24 01:22:27

In IE8/IE9, I'm unable to remove the 1px "3D" offset in the button's :active state.

@Tracker1 2012-07-25 20:59:38

@BrennanRoberts Yeah, unfortunately, any styling of buttons is more problematic with IE... I still feel it's probably the most appropriate approach, not that I don't break my own rules on occasion.

@Patrik Affentranger 2014-12-18 01:33:18

Then don't use <button> but an input type=button instead?

@Tracker1 2014-12-19 17:06:58

@PatrikAffentranger that will have the same issue with older IE versions... I've used the <a href="javascript:void(0)" onclick="...">...</a> method enough that it works... just suggesting that it's less than friendly for declaring intent with markup.

@tim 2015-05-13 01:39:17

I use a DIV tag. Easy styling, no fuss.

@joeytwiddle 2015-09-02 12:29:00

Then use a <clickable> element. Or a <clickabletim> if you prefer. Unfortunately, using a non-standard tag or a plain div might make it difficult for keyboard users to focus the element.

@mjsarfatti 2016-03-14 15:00:15

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.

@user5490177 2019-11-13 12:22:42

It will works like real links with button.link:hover{ text-decoration:underline; }

@Tracker1 2019-11-14 00:28:02

@Samad the text-decoration:underline is already present, default behavior is a slight color change though iirc.

@user5490177 2019-11-14 13:16:18

my purpose button.link{text-decoration:none} button.link:hover{text-decoration:underline}

@fijter 2008-09-25 18:59:47

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>

@AnthonyWJones 2008-09-26 07:09:01

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.

@Hosam Aly 2009-02-28 19:21:02

Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility.

@PeteT 2010-01-27 10:13:56

They boil down to the same thing it's semantics to use a span or an anchor tag. If the page url can only be generated in javascript it makes no difference where it's running from apart from as pointed out anchor tags can use keyboard navigation.

@redShadow 2011-12-14 23:15:58

<span>s are not meant to do anything. <A>nchors and <buttons> are used for that!

@apnerve 2012-12-28 08:33:06

Using buttons is a better choice here while using a span is not.

@NibblyPig 2014-04-09 17:00:54

I think a span is better than an anchor tag. Anchor tag exists to direct you to its mandatory href attribute. If you're not going to use the href, don't use an anchor. It doesn't restrict the link to mouse only because it isn't a link. It doesn't have a href. It's more like a button but it doesn't post. The span not being meant to do anything is completely invalid. Consider a dropdown menu that activates when you hover. It's probably a combination of spans and divs, performing the function of a button that expands an area on the screen.

@Dave Newton 2015-06-17 23:53:18

@SLC But a <span> is meaningless to a screen reader or accessible browser, no?

@Neurotransmitter 2016-08-15 11:10:10

Using buttons is often is a terrible idea from design point to trigger show/hide attributes of small divisions of a website, especially if there are plenty of these triggers. Lots of buttons in one place usually looks awful, if this is not some kind of a control panel. And as pointed earlier, anchors too are not designed to be JS triggers. So span or maybe even div looks like a better replacement, with their own downsides, but still better. There is nothing worse in the world than some gibberish in the href attribute. And also span handles middle-click better than anything.

@ps2goat 2016-12-12 18:51:11

I do this for cases where the user is not being directed somewhere, e.g., opening a modal. It's nice because then the middle button doesn't default to trying to open the link in a new tab. If I have something that navigates the user and they're allowed to open it in a new tab, I use a link (a tag with href) so users can open new tabs easily with middle mouse or ctrl + click. If I have something that navigates the user and I don't want them to open multiple tabs, then the button approach works.

@Zach 2008-09-25 17:56:53

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

@Quentin 2008-09-26 08:09:21

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.

@Zach 2008-09-26 15:41:58

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

@Brian Moeskau 2009-07-13 13:52:37

I would assume (hope) that something like this would only be for showing a popup or something similarly simple. In that case, the default would be the popup page url. If this is part of a web application, or having JS disabled would totally break the page, then this code has other issues...

@Zach 2009-07-13 23:08:02

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.

@Tracker1 2011-12-15 18:35:50

The issue is if myJsFunc throws an error, it won't be captured for the return false.

@Charlie 2017-10-04 19:47:25

Bootstrap modals from before 4.0 have a basically undocumented behavior that they will load hrefs from a elements using AJAX unless they are exactly #. If you are using Bootstrap 3, javascript:void(0); hrefs will cause javascript errors:

AJAX Error: error GET javascript:void(0);

In these cases you would need to upgrade to bootstrap 4 or change the href.

@Adam Tuttle 2008-09-25 17:55:34

'#' 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);

@Guvante 2008-09-25 21:22:54

The way to avoid that is to return false in the onclick event handler.

@Quentin 2008-09-26 08:10:02

Returning false in the event handler doesn't avoid that if JavaScript the JS doesn't run successfully.

@scunliffe 2008-09-27 02:46:32

using "#someNonExistantAnchorName" works well because it has nowhere to jump to.

@Abhi Beckert 2012-03-28 06:39:43

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.

@Lankymart 2013-07-18 12:06:22

Any use of # or void(0) is bad practice and shouldn't be encouraged.

@Neel 2014-04-17 00:23:12

The shebang (#!) does the trick but it's definitely bad practice.

@Ilya Streltsyn 2014-09-22 09:18:02

@Neel, any anchor that doesn't actually exist in the document (e.g. #_) does the same trick, with the same drawbacks.

@musicin3d 2017-05-03 11:31:55

@Neel At the first release of angular the author said something like, "best practices follow necessity," right before he put his script tags at the very bottom of the page.

@ehab 2019-12-15 11:21:33

@Guvante returning false will do absolutely nothing if this is a DOM-3 event, returning false is a jquery specific thing

@Guvante 2019-12-16 17:37:26

@ehab: html.spec.whatwg.org/multipage/… says "If return value is true, then set event's canceled flag." so I don't know what jquery specific thing you are talking about.

@user6460587 2016-10-29 19:10: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.

@Jochen Schultz 2017-09-21 10:58:26

Actually they don't do the same. # makes you jump to top of the page.

@Andrew Moore 2008-10-16 18:00:25

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.

@Free Consulting 2009-11-07 02:26:48

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.

@AnthonyWJones 2008-09-26 08:03:39

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.

@jakub.g 2013-10-01 09:21:52

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.

@Nathan 2014-02-14 04:58:32

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

@Garrett 2016-01-26 19:54:18

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

@Quentin 2016-06-15 12:12:48

Use a button, not a span. Buttons naturally fall in the focus order so can be accessed without a mouse / trackpad / etc.

@Tsundoku 2017-07-25 13:09:59

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.

@Useless Code 2017-11-22 11:45:07

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.

@Spammer Joe 2011-09-24 01:55:06

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

@cHao 2013-05-17 16:16:13

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.

@dnetix 2015-08-13 01:01:04

I usually go for

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

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

@CleverPatrick 2008-09-25 21:20:35

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.

@AndFisher 2017-01-18 14:42:33

Also if you were to replace an a with a span, you'll need to remember to make it focusable via keyboard.

@balupton 2012-02-25 02:08:18

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.

@Thomas Davis 2012-02-25 02:21:18

Be careful, leaving href attributes off is not cross browser compatible and you will lose out on things such as hover effects in internet explorer

@Christopher Camps 2012-07-10 02:02:07

I tend to agree with this answer, but there is another issue that arises from omitting the href attribute. In many browsers if you click the link multiple times very quickly it will actually select text on the page. Setting the href solves that particular problem which is not easy to fix otherwise.

@Brennan Roberts 2012-07-25 00:18:47

Beware: the link-styled button approach suggested here is plagued by the unavoidable "3d" active state in IE9 and lower.

@Jordan Rieger 2013-05-29 19:33:49

I find this answer to be overly dogmatic. There are times when you just want to apply the JS behavior to 1 or 2 a href's. In that case it's overkill to define extra CSS and inject a whole JS function. In some cases (e.g. adding content via a CMS) you are actually not allowed to inject new CSS or standalone JS, and inline is all you can do. I don't see how the inline solution is any less maintainable in practice for 1 or 2 simple JS a href's. Always be suspicious of broad general statements on bad practice, including this one :)

@Timo Huovinen 2013-06-08 09:23:16

It would make more sense to add 2 classes, one called cancel and the other action, then apply the css only to .action and the javascript only to .action.cancel

@user659025 2013-07-10 14:30:54

A full disagree here. While I also promote unobtrusive JavaScript, an anchor that has a "javascript:;" and it's actual events bound somewhere else is not bad practice. And it is always better than leaving the attribute out completely.

@Abhi Beckert 2013-07-18 15:00:00

With all those "notes" that are hard to solve (setting a tabindex is asking for trouble on a complex page!). Far better to just do javascript:void(0). That is the pragmatic answer, and the only sensible answer in the real world.

@jkade 2013-09-06 17:32:01

If you care about making your web application accessible (and you should), simplicity and sanity argues for href. Madness lies in the direction of tabindex.

@Jacob Mouka 2013-11-18 17:09:18

The missing href attribute is a problem. Many browsers don't display the link mouse cursor (yes, it can be added in CSS, but this is complicating things already) and I've seen some accessibility software ignore links without href (they are treated as just text). This answer has good ideas but the real world isn't as neat.

@Charles 2015-04-15 14:46:52

No, no, no!!! Don't EVER do this! You have just killed accessibility. Users with screen readers will no longer be able to use your application.

@Seega 2016-09-01 07:49:21

I'm agreeing with my two pre-posters. Without the href you are not even able to navigate through the links by using tabs. This answer should be deleted!

@TomDK 2017-03-26 23:37:26

According to sitepoint.com/community/t/anchors-without-href/6690/4 Screen-readers are fine with anchors that don't use href. The use of "#" is actually worse as it adds open in new tab functionality which only sends the use back to the original page at the top without the desired functionality.

@AlxGol 2014-11-18 15:42:45

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

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

@Alex Yorke 2014-12-29 20:20:32

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

@Martin 2017-03-14 14:18:59

As others have said, this cannot be activated using the keyboard.

@Hrvoje Golcic 2019-11-26 15:15:25

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

@AlxGol 2019-11-27 07:43:57

5 years after the answer I also consider the a11y features:)

@vol7ron 2012-08-22 16:08:03

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

});

@squidbe 2014-03-03 22:12:49

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.

@vol7ron 2014-06-02 16:13:33

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

@squidbe 2014-06-02 18:03:39

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.

@Anders M. 2014-03-20 10:55:57

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.

@Vinny Fonseca 2014-03-07 14:28:04

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.

@Ashish Kumar 2014-02-13 03:34:00

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.

Related Questions

Sponsored Content

46 Answered Questions

[SOLVED] Check if a value is an object in JavaScript

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

54 Answered Questions

3 Answered Questions

[SOLVED] Cannot display HTML string

28 Answered Questions

[SOLVED] Get selected value in dropdown list using JavaScript

27 Answered Questions

10 Answered Questions

[SOLVED] Improve INSERT-per-second performance of SQLite

8 Answered Questions

[SOLVED] Script Tag - async & defer

  • 2012-05-29 23:28:01
  • Adam
  • 234686 View
  • 582 Score
  • 8 Answer
  • Tags:   javascript html

Sponsored Content