DekGenius.com
Team LiB   Previous Section   Next Section
Link.onclick the handler invoked when a Link is clicked

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Synopsis

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

Description

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 to be displayed, it is better to use the onclick event handler of a Button object instead of the onclick handler of a Link object.

Note that while the onclick event handler returns false to tell the browser not to perform its default action (following a link), the onmouseover event handler must return true to tell the browser not to take its default action (displaying the URL of the link). This incompatibility exists for historical reasons. The standard for Form and form element event handlers is to return false to prevent the browser from performing a default action.

In the Netscape 4 event model, the onclick handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the hypertext link.

Bugs

In Netscape 3, the onclick event handler of the <area> does not work on Windows platforms. A workaround is to specify a javascript: URL as the value of the href attribute of the <area> tag.

See Also

Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

    Team LiB   Previous Section   Next Section