0

Is there a better way to define anchor links that perform javascript other than using href="#"? The main reason I dislike using this href is because it invalidates browser history. The back button just removes the "#" from the URL. If you use any type of Go Back link, it won't work unless they click it twice.

In cases where my Javascript is inlined, I can use href="javascript:func()", but this won't work when the listeners are attached from an external script file.

So I'm just looking for a cleaner direction to point my empty anchors.

Robert
  • 413
  • 4
  • 12
  • 2
    Unless you're using JavaScript to route to another page, you shouldn't be using anchors to begin with. Use buttons. – isherwood Mar 23 '21 at 19:18
  • Otherwise, there are a number of options here: https://stackoverflow.com/questions/134845/which-href-value-should-i-use-for-javascript-links-or-javascriptvoid0?rq=1 – isherwood Mar 23 '21 at 19:19
  • My issue is that I need to use both links and Javascript buttons in the same small section. Items of both types will be seen as the same group of buttons. So I would have to style both elements to look identical. But if that is the best approach, I may be able to give it a try. – Robert Mar 23 '21 at 22:19
  • That's how it's often done. :) – isherwood Mar 23 '21 at 23:52

2 Answers2

1

If you "MUST" use <a> tag for your actions, in such cases, I prefer to add preventDefault in the event listener. This prevents "#" from being added to the URL.

window.onload = function() {
  document.getElementById("noHash").addEventListener("click", function(e) {
    e.preventDefault();
    console.log("Hi There!");
  }); 
}
<a href="#" id="noHash">Say Hi</a>
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
0

I'm posting an alternate answer just so others who stumble onto this see that this is an option. When I asked about it, I didn't realize you could use the code href="javascript:void(0)". As far as I can tell, this doesn't have any negative side effects, and you can still attach click listeners to it later on.

In addition, the new HTML spec apparently states that anchor tags don't even need href attributes, and removing href attributes didn't seem to have any side effects in any browsers that I tried it in (Chrome, Firefox, Opera, Edge). Still, I stuck to the void option.

And finally, I read somewhere that another option is to use href="#!". I'm assuming this does nothing as long as you don't have an id of ! on your page, but I have not tested this one. EDIT: Tested this - it has the same issues as using href="#" by itself.

Robert
  • 413
  • 4
  • 12