Calling a Function on a HTML Link | How to Tutorial

Normally developers invoke a function or script with an onevent caller on the form elements, more specifically with the input tag using the onClick event handler. However there may be times when you would want to invoke a function/script when a user clicks on a hyperlink.

A code like onClick=myfunction() will not work in such a scenario. This is because the onClick event is bound to the form object and is not available outside of it.

However this can be easily achieved by calling the JavaScript link object which is a component of the document object hierarchy.

When you want to click a link to execute a script rather than navigate directly to another URL, you can redirect the HREF attribute to call a script function. To call a function, from a link you can use a pseudo-URL called the javascript: URL.

Sample code:


Click here to call a function

Notice the void keyword used in the above example.

This void keyword prevents the display of any value that may be returned by your function.

Also note that this technique can be applied to any html tag that has a href attribute.
So the following code is equally valid:


The image example shown above is used extensively for creating image maps on the client side.

You may perhaps at the end of the function like to direct the user to a new location.
In that case, you may add the location.href property to the end of your function:

location.href = "path/to/your/new/location"

A simple but complete working example and demo follows:

This goes into the header:

var newwindow
function myfunction() {
alert("you invoked the function myfunction()")
//then posibly redirect with
//location.href = "path/to/your/new/location"
//or stay on the same page if you wish.
}

And this into the body section:

Click to call a function

And here’s the actual demo: Click to call a function

One comment on “Calling a Function on a HTML Link | How to Tutorial

Comments are closed.