JavaScript events
HTML events are things that happen to HTML elements.
When JavaScript is used in an HTML page, JavaScript can trigger these events.
HTML events
HTML events can be browser behaviors or user behaviors.
The following are examples of HTML events:
HTML page completes loading
HTML input field changes
HTML Button Clicked
Normally, when an event occurs, you can do something.
JavaScript can execute some code when the event is triggered.
Event attributes can be added to HTML elements and JavaScript code can be used to add HTML elements.
Single quotes:
Double quotes:
In the following example, the onclick attribute (and code) is added to the button element:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <button onclick="getElementById('demo').innerHTML=Date()">现在的时间是?</button> <p id="demo"></p> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
In the above example, the JavaScript code will modify the content of the id="demo" element .
In the next instance, the code will modify the content of its own element (using this.innerHTML):
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <button onclick="this.innerHTML=Date()">现在的时间是?</button> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
![]() |
---|
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击按钮执行 <em>displayDate()</em> 函数.</p> <button onclick="displayDate()">点这里</button> <script> function displayDate(){ document.getElementById("demo").innerHTML=Date(); } </script> <p id="demo"></p> </body> </html>
Running instance»Click the "Run Instance" button to view the online instance
Common HTML eventsThe following is a list of some common HTML events:EventDescriptiononchangeHTML element changesonclickThe user clicks on an HTML elementonmouseoverThe user moves the mouse on an HTML elementonmouseoutThe user removes the mouse from an HTML elementonkeydownThe user presses a keyboard keyonloadThe browser has completed loading the page
More event lists: JavaScript Reference Manual - HTML DOM Events.
What can JavaScript do?
Events can be used to handle form validation, user input, user behavior and browser actions:
The event is triggered when the page loads
The event is triggered when the page is closed
The user clicks the button to perform the action
Verify the legality of user input
Wait...
You can use multiple methods to execute JavaScript event code:
HTML event attributes can directly execute JavaScript code
HTML event attributes can call JavaScript functions
You You can specify your own event handlers for HTML elements
You can prevent events from occurring.
Wait...
![]() |
---|