I do not recommend any of the options in the question, read on to know why.
In order to avoid usability problems if JavaScript support is disabled or if the visitor wants to open the link in a separate window, I usually leave the link handling in charge of the function responsible for opening it.
Let's see the case of jQuery and JavaScript
Link that will work even though 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
of the link and through the event object, we call the preventDefault()
method in order to prevent href
from being called, thus code that we want to execute.
JSFiddle Example
$('#meuLink').on('click', function (event) {
// prevenir comportamento normal do link
event.preventDefault();
// código a executar aqui
});
With JavaScript
With JavaScript, things are not as simple as we have to do some checks that these days are made by the frameworks that we like.
We hope the browser window has finished loading to ensure that we can add an event to the desired element and avoid calling href
.
Let's identify the element in the DOM, in this case via id
and save it in a variable.
Finally, we check the support that the browser is making available 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 minhaFuncao
function 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 given examples, try using the right mouse button to open the link on the next tab and thus check if the usability is intact!