Should I keep the void on the link or can I leave it blank?

1

I've seen some links that contain the following syntax:

<a href="javascript:;" id="el" onclick="acao()">

As far as I know, in some versions of IE this causes an error, so I ask if I should correct it by doing this:

 <a href="javascript:void(0);" id="el" onclick="acao()">

Of course some will say that I should do this separately, as in the examples below, but I would just like to know if I should keep "void(0)" or I can discard this rule:

(function(){
   var el = document.getElementById('el');
   el.addEventListener("click", acao());
});

Using the library as jQuery:

$(function(){
    $('#el').on('click', function(){
     acao();
    });
});
    
asked by anonymous 28.03.2016 / 14:40

1 answer

3

There is no good reason to use a javascript: pseudo-URL (*). In practice, this will cause confusion or errors.

<a href="#"> is a common alternative that can undoubtedly be less bad. However, you should remember to return false from your onclick event handler to prevent it from scrolling to the top of the page.

Example 1:

function foo() {
  alert('foo');
  return false;
}
<a href="#" onclick="return foo();">foo</a>

In some cases it is preferable to use #foo to dynamically show / hide elements.

Example 2:

function foo(el) {
  var id = el.getAttribute("href");
  document.getElementById(id).style.display = "inline";
  return false;
}
#foo {
  display: none;
}
 <a href="foo" onclick="return foo(this);">foo</a>
<div id="foo">div foo</div>

And if you plan to use jQuery you can use preventDefault:

Example 3:

$("a[href=#foo]").click(function(e) {
  foo();
  e.preventDefault();
});

function foo() {
  console.log('foo');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><ahref="#foo">foo</a>

Recommended reading:

28.03.2016 / 15:38