Categories
JavaScript Answers

How to prevent anchor behavior with JavaScript?

Spread the love

Sometimes, we want to prevent anchor behavior with JavaScript.

In this article, we’ll look at how to prevent anchor behavior with JavaScript.

How to prevent anchor behavior with JavaScript?

To prevent anchor behavior with JavaScript, we return false in the event handler.

For instance, we write

<a href="no-script.html" id="myLink">link</a>

to add a link.

Then we write

document.getElementById("myLink").onclick = () => {
  // ...
  return false;
};

to get the link with getElementById.

And then we set its onclick property to a function that’s called when the link is clicked.

We return false to stop the default behavior.

Conclusion

To prevent anchor behavior with JavaScript, we return false in the event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *