How to Write JavaScript Function as URL in Hyperlink?

You can write JavaScript function as like URL in hyperlink on href attribute of .... tag. Writing JavaScript codes in a URL is another way that JavaScript code can be included in the client side using javascript: protocol specifier. This special protocol type specifies that the body of the URL is an arbitrary string of JavaScript code to be run by the JavaScript interpreter.

The "resource" identified by a javascript: URL is the return value of the executed code, converted to a string. If the code has an undefined return value, the resource has no content.

You can use a javascript: URL anywhere you'd use a regular URL: on the href attribute of tag, on the action attribute of a
, on the click event of a button, on the method like window.open() etc.

The syntax for writing JavaScript function within href attribute of
tag is given below.

JavaScript Link

And the syntax for writing JavaScript function within the action attribute of a tag is given below.

.......

An example for getting new date using javascript function as a hyperlink is given below.

What time is it?

While using such functions on a hyperlink, some browsers like Firefox and IE execute the code in the URL and use the returned string as the content of a new document to display.

Just as when following a link to an http:URL, the browser erases the current document and displays the new one. The value returned by the code above does not contain any HTML tags.

Other browsers like chrome and safari do not allow URLs like the one above to overwrite the containing document, they just ignore the return value of the code. But they support the JavaScript code to display the returned content on alert box as below.

check the document without writing the docment

In the above cases, the javascript:URL serves the same purpose as an on-click event handler. The link The link above would be better expressed as an on-click handler on a

Open link on new window


If you want to open a new document using a javascript: URL which overwrite the current document, you can use location.replace method as given below.

Open window using location.replace


Like HTML event handler attributes, JavaScript URLs are a holdover from the early days of the web and generally avoided in modern HTML. JavaScript: URLs are very useful if you need to test a small snippet of JavaScript code, you can type a javascript:URL directly into the location bar of your browser. And another most powerful use of Javascript:URLs is in browser bookmarks.

Related Search Terms


Related Posts: