Home > Article > Web Front-end > How to write onclick event in js
The onclick event is an event handler in JavaScript that specifies code to be executed when an element is clicked. The steps are as follows: 1. Select the element, 2. Set the onclick attribute, 3. Define the function. Actions you can perform using the onclick event include changing styles, triggering navigation, opening modal windows, validating forms, and submitting data.
How to write the onclick event in JavaScript
The onclick event is an important event handler in JavaScript. Allows us to specify code to be executed when an element is clicked.
Syntax:
<code>element.onclick = function() { // 执行代码 };</code>
Steps:
Example:
In the following example, we will create a button and add an onclick event handler that when the button is clicked, it Will change the background color of the page:
<code><button id="myButton">点击我</button> <script> const button = document.getElementById("myButton"); button.onclick = function() { document.body.style.backgroundColor = "blue"; }; </script></code>
Other uses:
In addition to changing styles, the onclick event can also be used for:
Note: