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

Asked

Viewed 112 times

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 a mistake, so I ask if I should correct by doing this:

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

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

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

Using the library as jQuery:

$(function(){
    $('#el').on('click', function(){
     acao();
    });
});
  • 1

    Using jquery is always the best solution! :D always!

  • So, but my doubt is another... you read the question?

  • I edited the question to make it clearer.

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 no doubt 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 show/hide elements dynamically.

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>
<a href="#foo">foo</a>

Recommended reading[EN]: Href attribute for Javascript links: "#" or "javascript:void(0)"?

Browser other questions tagged

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