The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag

I recent ran into an interesting IE bug involving the following bit of html code:

<a href="javascript: void(0);" onclick="dosomething();">click me</a>

I honestly did not write this one but I will leave names out of this to protect the innocent =)

The void(0) JavaScript code is usually used to prevent loading or reloading of the page when the user clicks the link.

What we were trying to do here was have the dosomething JavaScript function execute when a user clicks on the link. This works fine in FireFox, Chrome, Safari but not IE. When a user clicks on the link in IE, nothing happens: i.e. (no pun intended) the JavaScript does not execute.

It took us a good amount of time to realize what the issue was with IE. It turns out that the void(0) function was preventing the onclick event to fire.

Although it may not be pretty, this is what we ended up doing and it appears to be cross-browser friendly:

<a href="<?=$_SERVER['PHP_SELF'];>#" onclick="dosomething(); return false;">click me</a>

Update: Here is an updated version of the code that accounts for users with JavaScript disabled:

<a href="[alternative link]" onclick="dosomething(); return false;">click me</a>

Thanks Ulrich for the suggestion! In this version, if a user has JavaScript disabled, a click on this link will take them to the [alternative link]. If JavaScript is enabled, then dosomething() will execute and the return false will prevent the browser from going to the [alternative link].

Anyway, I hope this helps someone out there in the universe.

How to find and access parent nodes via JavaScript


Have you ever had to access a parent node from a given child node? In this example, we are going to traverse up the DOM tree starting from the button to look for the parent node with the name attribute itsMe.

Demo
My name is notMe

My name is itsMe

My name is notMeEither

My name is tryAgain

My name is sorryNotMe

My name is nopeSorry

Continue reading How to find and access parent nodes via JavaScript

How to dynamically add content to a div and store the content to a cookie via JavaScript


This is an example of adding dynamic content via JavaScript by allowing the user type in the actual content.

Demo
Content to be added:


Your content will be added dynamically below:

Continue reading How to dynamically add content to a div and store the content to a cookie via JavaScript