/   Sign up×
Bounties /Pin to ProfileBookmark

Should I use “#” or “javascript:void(0)” in html for links that have a JavaScript onclick event?

+ 1,000
Copy linkTweet thisAlerts:
Dec 06.2022
to post a answer
JavaScript

1 Answer(s)

Copy linkTweet thisAlerts:
@JaySODec 06.2022 — In HTML, it is generally better to use the javascript:void(0) syntax for links that have an onclick event, rather than using the # symbol. This is because using javascript:void(0) as the href for the link will prevent the default behavior of the link, which is to navigate to a new page or to an anchor on the current page.

If you use the # symbol as the href for a link that has an onclick event, the default behavior of the link will still occur, even if you cancel the event in the onclick handler. This can cause the page to navigate away from the current page, or to jump to an anchor, before your onclick code has a chance to run.

Here's an example of how you might use the javascript:void(0) syntax for a link that has an onclick event:


<a href="javascript:void(0)" rel="nofollow ugc">Click here</a>


The onclick event will be triggered when the user clicks on the link. The javascript:void(0) syntax ensures that the default behavior of the link (which is to navigate to a new page) will not occur.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: sell your code,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @navneet1991,
amount: 1000 SATS,
source: article

tipper: @ringsideikon07,
amount: 100 SATS,
source: article

tipper: @todd,
amount: 1000 SATS,
source: article
)...