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>
void(0)
when void 0
will do? - anyone 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.
Answered 2023-09-20 20:11:28
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. - anyone href
. This would be done in jQuery with: $('a[href="#"]').click(function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; });
- anyone #void
would add an entry to the browser history nonetheless. Another way would be to use the URL of a resource that returns HTTP status 204 (and still use preventDefault
- the 204 is just a fallback). - anyone const voidLinks = document.querySelectorAll('a[href="#"') for (const voidLink of voidLinks) { voidLink.addEventListener('click', e => { e.preventDefault ? e.preventDefault() : e.returnValue = false }) voidLink.addEventListener('keypress', e => { if (e.keyCode === 13) e.preventDefault ? e.preventDefault() : e.returnValue = false }) }
That is including event listener on keypress Enter (code 13) for people navigation through page with keyboard. - anyone void
is an operator, not a function. It’s void 0
; the parentheses in void(0)
don’t do anything. void()
is just as invalid as, say, return ();
. ()
is not a valid UnaryExpression. - anyone 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).
Answered 2023-09-20 20:11:28
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:
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.
You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.
There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.
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
// 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>
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!
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.
Answered 2023-09-20 20:11:28
'#'
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);
Answered 2023-09-20 20:11:28
#
or #something
will take you to that anchor on the base href page, instead of on the current page. - anyone #!
) does the trick but it's definitely bad practice. - anyone 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.
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.
Answered 2023-09-20 20:11:28
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. - anyone 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>
.
Answered 2023-09-20 20:11:28
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>
Answered 2023-09-20 20:11:28
<span>
s are not meant to do anything. <A>
nchors and <buttons>
are used for that! - anyone buttons
is a better choice here while using a span
is not. - anyone <a>
tag.” — Even if the JavaScript code is “for navigation”, a link may not be appropriate every time. - anyone 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.
Answered 2023-09-20 20:11:28
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,
.
Answered 2023-09-20 20:11:28
#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. - anyone a
when clicked (onclick
) - anyone I use the following
<a href="javascript:;" onclick="myJsFunc();">Link</a>
instead
<a href="javascript:void(0);" onclick="myJsFunc();">Link</a>
Answered 2023-09-20 20:11:28
href="javascript:"
and href="javascript:void 0;"
are all equivalent as well, but they’re all equally bad. - anyone 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.)
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
#
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.
Answered 2023-09-20 20:11:28
click
on links… - anyone 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.
Answered 2023-09-20 20:11:28
Definitely hash (#
) is better because in JavaScript it is a pseudoscheme:
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.
Answered 2023-09-20 20:11:28
I usually go for
<a href="javascript:;" onclick="yourFunction()">Link description</a>
It's shorter than javascript:void(0) and does the same.
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
I would use:
<a href="#" onclick="myJsFunc();return false;">Link</a>
Reasons:
href
simple, search engines need it. If you use anything else ( such as a string), it may cause a 404 not found
error.return false;
, the page doesn't jump to the top or break the back
button.Answered 2023-09-20 20:11:28
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;
}
Answered 2023-09-20 20:11:28
span
element because it is a non-focusable element. That's why you need a button. - anyone 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. - anyone 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.
Answered 2023-09-20 20:11:28
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!
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
If you happen to be using AngularJS, you can use the following:
<a href="">Do some fancy JavaScript</a>
Which will not do anything.
In addition
false
with JavaScriptAnswered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
a
with a span
, you'll need to remember to make it focusable via keyboard. - anyone 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.
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
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.
Answered 2023-09-20 20:11:28
When I've got several faux-links, I prefer to give them a class of 'no-link'.
Then in jQuery, I add the following code:
$(function(){
$('.no-link').click(function(e){
e.preventDefault();
});
});
And for the HTML, the link is simply
<a href="/" class="no-link">Faux-Link</a>
I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).
<a href="javascript:void(0)" class="no-link">Faux-Link</a>
Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.
Answered 2023-09-20 20:11:28
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).
Answered 2023-09-20 20:11:28
javascript:void(0);
is also not good if you want to use a strict Content Security Policy that disables inline JavaScript. - anyone