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
##JavaScript code is usually a few lines of code. The more common one is to call it through event attributes: |
---|
<!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:
Description | |
---|---|
HTML element changes | |
The user clicks on an HTML element | |
The user moves the mouse on an HTML element | |
The user removes the mouse from an HTML element | |
The user presses a keyboard key | |
The browser has completed loading the page |
##In HTML DOM In this chapter you will learn more about events and event handlers. |
---|