0

I have seen implementing onclick on a element in different ways, but i don't know How each one different from another in event?

What i want when i click on a i would like to have onclick event happen without href do nothing.

<a href="#" onclick="myFunc()">Submit</a>
<a href="javascript:void(0);" onclick="myFunc()">Submit</a>
<a href="javascript:;" onclick="myFunc()">Submit</a>
Which is the appropriate one to use in my case?

Srinivas
  • 464
  • 3
  • 17
  • 1
    Possible duplicate of [Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?](https://stackoverflow.com/questions/134845/which-href-value-should-i-use-for-javascript-links-or-javascriptvoid0) – Rax Weber Nov 19 '17 at 15:36
  • 1
    Possible duplicate of [How can I disable HREF if onclick is executed?](https://stackoverflow.com/questions/15622100/how-can-i-disable-href-if-onclick-is-executed) – Fabian Lauer Nov 19 '17 at 15:37

1 Answers1

1

In JS development today none of those examples is really appropriate because inline JavaScript is pretty much frowned on - separation of HTML/JS is the best route to take.

So, in a separate JS file called from your HTML page (place the <script> just before </body> to ensure the DOM loads before the script is executed), grab your anchors, and add an event listener to each one that calls the corresponding function.

let anchors = document.querySelectorAll('a');
[...anchors].forEach(anchor => anchor.addEventListener('click', handleAnchor, false));

Then in your function, make sure you pass in the event, and call preventDefault() to stop the disable the href.

function handleAnchor(e) {
  e.preventDefault();
  ...
}

MDN resources

Andy
  • 61,948
  • 13
  • 68
  • 95