Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What “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>
by

2 Answers

Bharatgxwzm
I would sincerely recommend not one or the other. I would utilize an adapted <button></button> for that conduct
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>


On the off chance that you MUST utilize A component, use javascript:void(0); for reasons previously referenced.

Will consistently block on the off chance that your onclick occasion fizzles.

Won't have wayward burden calls occur, or trigger different occasions dependent on a hash change

The hash tag can cause sudden conduct if the snap fails to work out (onclick tosses), keep away from it except if it's a suitable fall-through conduct, and you need to change the route history.
MounikaDasa
As far as my knowledge 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>.

Login / Signup to Answer the Question.