One of the techniques often used in html are hyperlinks that actually do not take the user to another page, but instead run a client-side javascript, dhtml.
The most common way of programming hyperlinks in html is done by using the A (anchor) tag. The following code snippet illustrates the ease of creating a hyperlink:
<a href="http://www.hashemian.com/">www.hashemian.com</a>
Since the A tag has been with us since the inception of the Web, most people have come to expect that clicking on them causes an action. And even the most novice of html programmers are familiar with the tag.
Things however can get more complicated if you need the hyperlink click do something other than redirecting the user to another page. For example, you want to pop up a message, populate a field, syntax-check the user's input, or other client-side tasks. You know, dynamic html (dhtml) stuff. Enter the javascript:void(0) function. I ran into this feature years ago while searching for something, and I've been a loyal user ever since. The javascript:void(0) function basically neuters the hyperlink while allowing you to carry out some dhtml activity within the onClick event, i.e.:
<a href="javascript:void(0)" onclick="alert('You clicked.')" >www.hashemian.com</a>
The void() function causes the browser to take no redirection action upon clicking. In most modern, javascript-literate browsers you can accomplish the same disarming task by adding a "return false;" at the end of the onClick event code, but you'd still need to provide something in for the href property, so might as well make it javascript:void(0).
The story of void() doesn't quite end here. Although javascript:void(0) is the most widely used form of the void() function, you can actually have it invoke a javascript function like so:
<a href="javascript:void(alert('You clicked.'))" >www.hashemian.com</a>
This obviates wiring up the onClick event altogether. As always, your mileage may vary depending on your browser, so test your pages thoroughly. <JavaScript void function and html hyperlinks>
// posted by rh
3 Comments:
By , at
9/11/06 10:02 PM
Posted 6:16 6/5/2005
Thanx for the javascript counter man. its one of the best out there and also very simple.
Good work...
By , at
18/12/06 10:26 AM
I second the above post. Well done.
By , at
1/5/08 12:54 PM
Be careful with void(0) in Internet Explorer (that should come as no surprise)
In particular, binding an onclick event handler to an anchor tag in IE, that also has the void href, will prevent the bound click event from firing.
Post a Comment