HTML/JavaScript onclick() Event

HTML or JavaScript provides the onclick() event, in order to fire some actions when an HTML element, is clicked. The onclick() event can be used with different HTML elements like buttons, labels, text, etc. The JavaScript function or script is set as the onclick() attribute value to take some action.

onclick Attribute Syntax

The onclick attribute is located inside the HTML element tag. The value of the onclick can be set inside the double-quote or without any quote.

  • ELEMENT is the HTML element name which can be a text, button or label, etc.
  • JAVASCRIPT is the JavaScript code or function which will be executed when the ELEMENT is clicked.
  • TEXT is the ELEMENT text or data.

Run JavaScript Code with onclick()

The onclick attribute can be used to run JavaScript code inside the HTML element directly. This provides a practical way to take action against the click event. In the following example, we show an alert when the button is clicked.

<button onclick="alert(Hello Wisetut)">Wisetut</button>

Run JavaScript Function with onclick()

Another popular or may be the most popular way to use the onclick is calling a JavaScript function. The JavaScript functions can be created inside the HTML element or included as an external file. In the following example, we call the function named update() when the button is clicked.

<button onclick="update()">Wisetut</button>