Use HREF javascript:void(0) vs HREF Hashtag #

Upon working with websites wherein you will have to prototype a reuseable section — for example a banner with links that aren’t active yet — you might be wondering what value to use for the HREF attribute, or if none at all?

The answer is that it is better not to use href="#", since this may cause the browser to scroll towards the top of the screen, since it couldn’t find the anchor #.

A better approach is to use the href="javascript:void(0);", or shorthand to use href="javascript:;". This way, you will be able to use non-disabled links e.g. when working with buttons in the Twitter Bootstrap Framework, since Bootstrap provides a different styling for buttons or .btn classes without an href attribute.

The link towards this discussion can be found within Stack Overflow: Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?.

But This Violates Content Security Policy (CSP) Enabled Websites!

Stack Overflow user jakub.g figured out that javascript:void(0) violates CSP-enabled websites.

However for the most part you will have to double-check that the HTTP headers used in the website you are developing may involve using the Content Security Policy header. If this is the case, then it is better to forgo the use of javascript:void(0).

What can be done instead will be to make it known throughout the project of the following convention you will have to put in place:

Instead, use href="#void" for links that don’t have a proper URL yet in the web project

This way, when a user clicks on an HTML element with an HREF attribute of value #void, the browser will look around for a non-existing anchor, without scrolling to the top of the page.

The Bottomline

Regardless of having a Content Security Policy enabled on the web project, it will be a lot easier to use the href="#void" approach, as this avoids having to find out whether a CSP header is on a certain webpage deep within the website.

The only thing though would be to create a convention that the ‘placeholder’ links will be linked as #void.

What do you think?