Attribute "href" for Javascript links: "#" or "javascript:void(0)"?

Asked

Viewed 90,884 times

21

Popularly, there are two methods of creating links that perform a function in Javascript, are they:

<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

25


None.

Problems

  • Using any of these examples promotes "obstructive Javascript" which makes the code difficult to maintain and not scalable at all.
  • Use javascript:void(0) does not allow users to open this link in a new tab, which can be frustrating.
  • Use javascript:void(0) violates the Content Security Policy (CSP) on secure pages (HTTPS).
  • Use # makes the user go back to the top of the page and needs a return false; to make it work properly.

Completion

In my opinion, the tag button is more recommended than tag a, it can even take on the appearance of a CSS link:

.link {
  background-color: transparent;
  border: 0;
  color: #00f;
  cursor: pointer;
  display: inline-block;
  padding: 0;
  position: relative;
  text-decoration: underline;
}

If using the tag button is not an option, the best way to write your code in these cases is by removing the attribute href, you are not required to use it at all. Any good CSS reset, like the Normalize takes care of the default setting of the cursor style, 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);

Remarks

  • Remove the attribute href of a causes an accessibility problem, as the element is no longer accessible through the navigation by the key tab. You can define a tabindex or replace with a button, that can easily take on the appearance of a link.
  • Remove the attribute href of a causes problems related to hover in versions 6 and 7 of Internet Explorer. If necessary, this can be easily solved with Javascript.
  • If you want your link to continue working if Javascript is disabled, use the element href and insert event.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 to javascript:void(0) because it will cause less trouble.

Bonus

There is another method, which is the use of an anchor not existing by default, as in the example below:

<a href="#void" onclick="myFunction();">Executar JavaScript</a>

This method is very similar to the examples shown, although this way the page will not go up. Even so the code remains obstructive.

  • Why do you recommend using the button? What would be the advantage?

  • @Joaopaulo: Semantically, the tag button is the most recommended to perform actions and tag a should be used only to point the user to other pages, internal or external.

10

Don’t use any of the options

Why?

First, the allocation of Event Handler should not be made inline. HTML is for marking and structuring content, all behavior should be separated, in Javascript file(s). Violate this principle and you will see how easy it is to turn the code into a salad (or, as the gringos say, a spaghetti).

So don’t use onclick="myFunction();". Instead, ensure that the element will be easily accessible via Javascript by assigning it an id or class (of course not even this is 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 anything else that makes sense. A <a> without href is valid HTML5, but a href with a value that is not URL is invalid. And even if the anchor has href, it is very simple to avoid 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');
});

9

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.

  1. 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.
  2. We will identify the element in the DOM, in this case through the id and store it in a variable.
  3. 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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.