Do not recommend any of the options in the question, continue to read to know 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 see the case of jQuery and Javascript
Link that will work even if Javascript support is disabled in the visitor’s browser:
<a href="minha_pagina.html" id="meuLink">Abrir</a>
With jQuery
With jQuery, we attach a click event to id
or class
link and through the event object, we call the method preventDefault()
in order to prevent the href
be called, thus giving rise to the code we intend to execute.
Example in Jsfiddle
$('#meuLink').on('click', function (event) {
// prevenir comportamento normal do link
event.preventDefault();
// código a executar aqui
});
Javascript-enabled
With Javascript, things are no longer so simple, because we have to do some checks that nowadays are performed by the frameworks that we like so much.
- We hope that the browser window has finished loading to garland that we will be able to add an event to the desired element and avoid calling the
href
.
- We will identify the element in the DOM, in this case through the
id
and store it in a variable.
- Finally, we checked the support the browser is providing us to attach the click event to the link.
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
gets 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!
Why do you recommend using the button? What would be the advantage?
– Joao Paulo
@Joaopaulo: Semantically, the tag
button
is the most recommended to perform actions and taga
should be used only to point the user to other pages, internal or external.– Caio Tarifa