Link.onclick — the handler invoked when a Link is clicked


JavaScript 1.0; enhanced in JavaScript 1.1


<a ... onclick="handler" ... >
<area ... onclick="handler" ... >


The onclick property of a Link object specifies an event handler function that is invoked when the user clicks on the link. The initial value of this property is a function that contains the JavaScript statements specified by the onclick attribute of the <a> or <area> tag that defined the Link object. When an event handler function is defined in this way by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

The onclick event handler is invoked before the browser follows the clicked hypertext link. This allows you to dynamically set href, target, and other properties of the link (using the this keyword to refer to the clicked link). You may also use the methods Window.alert( ), Window.confirm( ), and Window.prompt( ) from this event handler.

In JavaScript 1.1, you may prevent the browser from following the link by returning false. If you return true, any other value, or nothing, the browser follows the link as soon as onclick returns. You might stop the browser from following a link if you use the Window.confirm( ) method to ask the user if he really wants to follow the link and the user chooses the Cancel button, for example. In general, if you want a link that performs some action but does not cause a new URL ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.