"Href" attribute for links in JavaScript: "# " or " javascript: void (0)"?
Popularly, there are two methods of creating links that perform a function in JavaScript, they are:
<a href="#" onclick="myFunction();">Executar JavaScript</a>
Or
<a href="javascript:void(0)" onclick="myFunction();">Executar JavaScript</a>
Considering functionality, page loading, etc... Which is the most recommended?
3 answers
None.
Problems
- using any of these examples promotes "obstructive JavaScript" which makes the code difficult to maintain and not scalable at all.
- using
javascript:void(0)
does not allow users to open this link in a new tab, which can be frustrating. - using
javascript:void(0)
violates content security policy (CSP) on secure pages (HTTPS). - using
#
causes the user to return to the top of the page and you need areturn false;
for it to work properly.
Conclusion
In my opinion, the tag button
is more recommended than the tag a
, it can even assume the appearance of a link with CSS:
.link {
background-color: transparent;
border: 0;
color: #00f;
cursor: pointer;
display: inline-block;
padding: 0;
position: relative;
text-decoration: underline;
}
If the use of the button
tag is not an option, the best way to write your code in these cases is to remove the href
attribute, you do not have to use it at all. Any good CSS reset , such as Normalize takes care of default cursor style definition, so that usability can be maintained. In addition, for you to have scalable, easy-to-maintain code, your logic needs to "stay" in JavaScript itself.
Example:
Your HTML:
<a class="action">Ação</a>
Your JavaScript:
var actionButton = document.querySelector('.action');
actionButton.addEventListener('click', myFunction);
/* Usando jQuery */
$('.action').on('click', myFunction);
Comments
- removing the
href
attribute froma
causes an accessibility problem, as the element is no longer accessible through key navigationtab
. You can define atabindex
or replace it with abutton
, which can easily take on the appearance of a link. - removing the
href
attribute froma
causeshover
- related issues in Internet Explorer versions 6 and 7. If necessary, this can be easily solved with JavaScript. - if you want your link to continue working if JavaScript is disabled, use the
href
element and enterevent.preventDefault()
at the end of the JavaScript code action. This is a great example of graceful degradation . - in extreme cases, where JavaScript code control is limited, the best option is
javascript:void(0)
as it will cause the least problems.
Bonus
There is another method, which is to use a non-existing anchor by default, as in the example below:
<a href="#void" onclick="myFunction();">Executar JavaScript</a>
This method is very similar to the examples presented, although in this way the page will not go up. Even so the code continues being obstructive.
Do not use any of the options
Why?
First, the assignment of the event handler should not be done inline. HTML is for content markup and structuring, all behavior must be separate, in JavaScript file (s). Violate this principle and you will see how easy the code is to turn a salad (or, as the gringos say, a spaghetti).
So do not use onclick="myFunction();"
. Instead, ensure that the element will be easily accessible via JavaScript, assigning it an id or class (of course this is not even necessary to select the element in JavaScript, but it is usually more convenient). The element can be an anchor without href, a simple span, a button, or something else that makes sense. A <a>
without href is valid HTML5, but an href with a value other than URL is invalid. And even if the anchor has href, it is very simple to prevent via js that the link is followed.
I would use the following:
<a id="el" href="http://example.com">Não me siga</a>
// De preferência em arquivo à parte
document.getElementById('el').addEventListener('click', function(e){
// Não siga o link!
e.preventDefault();
alert('não segui');
});
I don't recommend any of the options in the question, read on to find out why.
To avoid usability problems in case JavaScript support is disabled or in case the visitor wants to open the link in a separate window, I usually leave the processing of the link to the function responsible for opening it.
Let's look at the case of jQuery and JavaScript
Link that will work even if JavaScript support is disabled in the visitor browser:
<a href="minha_pagina.html" id="meuLink">Abrir</a>
With jQuery
With jQuery, we attach a click event to the id
or class
of the link and through the event object, we call the method preventDefault()
in order to prevent the href
from being called, thus giving way to the code we intend to execute.
$('#meuLink').on('click', function (event) {
// prevenir comportamento normal do link
event.preventDefault();
// código a executar aqui
});
With JavaScript
With JavaScript, things are no longer so simple as we have to do some checks that these days are carried out by the frameworks that we like so much.
- We hope that the browser window has finished loading to ensure that we will be able to add an event to the desired element and avoid calling
href
. - let's identify the element in the DOM, in this case through the
id
and save it in a variable. - finally, we check the support that the browser is making available to us to attach the link click event.
Example in JSFiddle .
// Esperar que a "window" tenha terminado de carregar
window.addEventListener('load', function() {
// apanhar o elemento para uma variável
var element = document.getElementById('meuLink');
// verificar suporte e reagir em conformidade
if (element.addEventListener) {
element.addEventListener('click', minhaFuncao, false);
} else if (element.attachEvent) {
element.attachEvent('onclick', minhaFuncao);
}
}, false);
And the function minhaFuncao
looks like this:
function minhaFuncao(e) {
// prevenir comportamento normal do link
e = e || window.event;
e.preventDefault();
// código a executar aqui
}
Note: in the examples given, Try using the right mouse button to open the link in a tab next to it and check if the usability is intact!