Srinivas
Srinivas

Reputation: 554

Implement onclick on anchor element while omitting href

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?

Upvotes: 0

Views: 238

Answers (1)

Andy
Andy

Reputation: 63587

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

Upvotes: 1

Related Questions