Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

The onclick attribute

The onclick attribute contains JavaScript that handles a click event. Distinguish it from the element.onclick property.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onclick="JavaScript statements"

All HTML elements support onclick. Its value is a JavaScript function body, not a URL. The code runs when handling a click event.

Inside the attribute, event is the event and this is the handling element, not necessarily event.target. The text attribute onclick and the element.onclick property, which accepts a function or null, control the same handler slot; assigning a function replaces the previous handler.

return false cancels the event if cancelable; it does not stop propagation. Content Security Policy can block attribute code. Do not insert untrusted content into it.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>onclick example</title>
</head>
<body>
  <button type="button" onclick="this.textContent = 'Done';">Run</button>
</body>
</html>

Result

Done

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources