Hashemian Blog
Web, Finance, Technology

JavaScript void function and html hyperlinks

    📂 Uncategorized         🗨 No Comments

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.

Your Comment


* Comments are subject to screening and manual approval.

Read Financial Markets  |   Home  |   Web Tools  |   Blog  |   News  |   Articles  |   FAQ  |   About  |   Privacy  |   Contact
Give a few Sats: 1GfrF49zFWfn7qHtgFxgLMihgdnVzhE361
© 2001-2024 Robert Hashemian   Powered by Hashemian.com