"href" attribute for JavaScript links: "#" or "javascript: void (0)"?

20

Popularly, there are two methods of creating links that execute 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 load, etc ... Which is the most recommended?

    
asked by anonymous 21.12.2013 / 02:50

3 answers

22

None.

Problems

  • Using any of these examples promotes "Obstructive JavaScript" which makes code hard to maintain and scalable.
  • 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 the Content Security Policy (CSP) on secure pages (HTTPS ).
  • Using # causes the user to go back to the top of the page and needs return false; to work correctly.

Conclusion

In my opinion, the button tag is more recommended than the a tag, it can even take on 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 , 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 the 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);

Observations

  • Removing the href attribute from a causes an accessibility problem because the element is no longer accessible by navigating with the tab key. You can set a tabindex or replace with a button , which can easily assume the appearance of a link.
  • Removing the href attribute from a causes problems related to hover in versions 6 and 7 of Internet Explorer. If needed, this can be easily solved with JavaScript.
  • If you want your link to continue to work if JavaScript is disabled, use the href element and enter event.preventDefault() at the end of the JavaScript code action. This is a great example of graceful degradation .
  • In extreme cases, where control of JavaScript code is limited, the best option is javascript:void(0) because it will cause less problems.

Bonus

There is another method, which is to use an anchor that does not exist 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 this way the page will not rise. Even so, the code remains obstructive.

    
21.12.2013 / 02:50
10

Do not use any of the

Why?

First, the assignment of the event handler should not be done inline . HTML is for marking and structuring content, all behavior must be separate, in JavaScript file (s). Viole this principle and see how easy it 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, giving it an id or class (of course, this is not even necessary to select the element in JavaScript, but 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 a href with a value other than 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');
});
    
21.12.2013 / 03:17
9

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!     

    21.12.2013 / 03:46