What is a web page after all? Isn't it a bunch of information linked to something else?
As you know, web sites without links don't exist. And if they exist they are basically dead. When we insert a link in a page, we generally want people to click on it and go somewhere else. However, some times we need to create links that do nothing. Or to better say, links that do not take the user somewhere else.
On the other side, here we are talking about something different. We will see how to use void(0), but we will see something else and we will make some considerations about it.
is perfectly working and when clicked, the link will open an alert box.
In the above example, we are doing something very simple, but what if we need to do something more complicated? That's when we need to use void(0).
Void(0) is always returning a null value, avoiding the load of a new page if used in a link:
The above snippet will produce a link which does nothing when clicked.
What's the whole use of it then?
A simple example you can find on the Internet is the following:
We set myVal to 10 and show it with an alert box. Simple as that. Everything is inside the link itself.
Ok... but... is all the above good?
First of all, some of you might have risen an eyebrow: "Why don't we use onClick?".
Good question. And I generally agree with that. I do prefer to use onClick even if in a different way. However, should we use:
<a href="#" onClick="myJsFunc();">Link</a>
Some says the first solution, some the second. And the reasons are quite important in both cases.
Generally developers prefer the void(0) solution, but there's something else about it which is more important. And this is my opinion.
Ok, it's my opinion! It counts for what it counts.
Hyperlinks should be used to link to something else. It's a bad practice to use links that do nothing. Or better, links that are not links should not be used.
If we need to perform an action when a user clicks an element of the page, we can use the onClick event directly in the element. We can, for example, use jQuery (as I said at the beginning of the post) with a styled element (a div for example) that trigger some action when clicked.
Other solution: we can use a button. A button is born to be pushed. I know you might argue that a link is the same. However links are born to be clicked to go somewhere else. Buttons are born to be clicked in order to perform other action.
I believe it will be an open debate. But I would like to know what you think about it. Please leave a message in the comments section below, if you want to share your thoughts.