3 javaScript:void alternatives

3 javaScript:void alternatives

Originally published on tronic247.com/3-javascriptvoid-alternatives

Need to write a sponsored post? Email posandumapa at gmail.com

In this article, you will learn some javaScript: void alternatives. Before we begin, I will do a brief introduction about javascript: void.

What is it?

We use javascript: void when there's a link that we don't want to change webpage. So when a user clicks the link nothing will happen. This is mostly used in demo webpages, etc. So let's see the alternatives.

Using e.preventDefault;

We can set href="#" to the link and add a class event and add this javascript code.

const links = document.querySelectorAll("a.event");
if (links) {
    links.forEach((link) => {
        link.addEventListener("click", (e) => {

Now, when we click the link nothing happens.

Using #!

This is the easiest method. When we set href="#", if the page is scrolling, it will scroll up. But if we set href="#!" it will stay the same. See the example below.

Do you get it?

Using return false

Using onclick="return: false" andhref="#"` also works.

Using a button instead of a

Using a button element instead of the a element also works. But if you want to use a link and can't live without it, you can use the methods I used before.


Now that we know some alternatives I recommended you use href="#!" that is more effective. See you in the next article. And also you can see more articles like this in tronic247.com