Hashemian Blog
Web, Finance, Technology, Running

May 5, 2005

JavaScript void function and html hyperlinks

Filed under: Uncategorized — robert @ 11:00 pm

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.

No Comments »

 
* Spammers: All comments are Akismet-verified and then manually checked before being approved.

Powered by


Read Financial Markets  |   Home  |   Blog  |   Web Tools  |   News  |   Articles  |   FAQ  |   About  |   Contact

© 2001-2012 Robert Hashemian
Support the effort
Liked this page?
Please consider creating a link to it
from your Web site.

hashemian.com
هاشمیان.com

Home
Blog
Web Tools
News
Articles
FAQ
About
Contact
Financial Markets

Visits: Powered by hashemian.com

Search Hashemian.com