JavaScript even...LOGIN

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:

<some-HTML-element some-event='some JavaScript'>

Double quotes:

<some-HTML-element some-event="some JavaScript">

In the following example, the onclick attribute is added to the button element (and the code is added) :

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>

In the above example, the JavaScript code will modify the content of the id="demo" element.

Run the code and try it

In the next instance, the code will modify the content of its own element (using this.innerHTML):

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
</head>
<body>
<button onclick="this.innerHTML=Date()">现在的时间是?</button>
</body>
</html>

Run the code and try it


Tip: JavaScript code is usually a few lines of code. The more common one is to call it through event attributes:


Common HTML events

The following is a list of some common HTML events :

EventDescription
onchangeHTML element changes
onclickThe user clicks on an HTML element
onmouseoverThe user moves the mouse on an HTML element
onmouseoutThe user removes the mouse from an HTML element
onkeydownThe user presses a keyboard key
onloadThe browser has completed loading the page

What can JavaScript do?

Events can be used to handle form validation, user input, user behavior and browser actions:

  • Triggered when the page loads

  • Event fired when the page is closed

  • Event triggered when the user clicks the button to perform the action

  • Verify the legality of user input

  • Wait...

You can use a variety of Method to execute JavaScript event code:

  • HTML event attribute can directly execute JavaScript code

  • HTML event Attributes can call JavaScript functions

  • You can specify your own event handlers for HTML elements

  • You can prevent events from happening.

  • etc...



Next Section
<!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>
submitReset Code
ChapterCourseware