2cBGj7vsfp
2cBGj7vsfp

Reputation: 2717

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

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>

Upvotes: 4453

Views: 2517479

Answers (30)

Henry
Henry

Reputation: 1270

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.

Upvotes: 0

Tracker1
Tracker1

Reputation: 19344

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

Upvotes: 356

Danny Beckett
Danny Beckett

Reputation: 20806

Why not just completely omit the href? Like so:

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

Upvotes: -3

CleverPatrick
CleverPatrick

Reputation: 9491

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

Upvotes: 16

Andrew Moore
Andrew Moore

Reputation: 95424

Usually, you should always have a fallback link to make sure that clients with JavaScript disabled still have 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.

Upvotes: 22

Timo Huovinen
Timo Huovinen

Reputation: 55653

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.

Upvotes: 2

SchoolforDesign
SchoolforDesign

Reputation: 455

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.

Upvotes: 1

Nedim AKAR
Nedim AKAR

Reputation: 143

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

Upvotes: 0

Stokely
Stokely

Reputation: 15887

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>

Upvotes: 4

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

Upvotes: 71

Dev pokhariya
Dev pokhariya

Reputation: 346

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

Upvotes: 9

Javed Khan
Javed Khan

Reputation: 395

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>

Upvotes: 4

TomDK
TomDK

Reputation: 1411

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.

Upvotes: 15

Milan and Friends
Milan and Friends

Reputation: 5610

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.

Upvotes: 16

Matt Goddard
Matt Goddard

Reputation: 909

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

Upvotes: 9

L Y E S  -  C H I O U K H
L Y E S - C H I O U K H

Reputation: 5090

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.

Upvotes: 8

mmacaulay
mmacaulay

Reputation: 3049

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

Upvotes: 14

user564706
user564706

Reputation: 33

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.

Upvotes: 30

se_pavel
se_pavel

Reputation: 2208

I use the following

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

instead

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

Upvotes: 73

fijter
fijter

Reputation: 18077

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>

Upvotes: 110

Zach
Zach

Reputation: 24786

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

Upvotes: 153

Adam Tuttle
Adam Tuttle

Reputation: 19834

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

Upvotes: 360

user6460587
user6460587

Reputation:

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.

Upvotes: 15

Free Consulting
Free Consulting

Reputation: 4402

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.

Upvotes: 40

AnthonyWJones
AnthonyWJones

Reputation: 189505

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.

Upvotes: 2318

Garrett
Garrett

Reputation: 3023

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

Upvotes: 25

Spammer Joe
Spammer Joe

Reputation: 41

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

Upvotes: 79

dnetix
dnetix

Reputation: 330

I usually go for

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

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

Upvotes: 33

balupton
balupton

Reputation: 48709

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.

Upvotes: 810

AlxGol
AlxGol

Reputation: 156

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

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

Upvotes: 8

Related Questions