Home >Web Front-end >JS Tutorial >Events in JavaScript Tutorial_Basics
Events are behaviors that can be detected by JavaScript.
Events
JavaScript gives us the ability to create dynamic pages. Events are behaviors that can be detected by JavaScript.
Every element in a web page can generate certain events that can trigger JavaScript functions. For example, we can generate an onClick event to trigger a function when the user clicks a button. Events are defined in HTML pages.
Event examples:
Mouse click
Page or image loading
Mouse hovering over a hot spot on the page
Select input box in the form
Confirm form
Keyboard keys
Note: Events are usually used in conjunction with functions, and the function will be executed when the event occurs.
If you need more comprehensive knowledge about the events that Javascript can recognize, please read our complete "Event Reference Manual".
onload and onUnload
The onload and onUnload events are triggered when the user enters or leaves the page.
onload event is often used to detect the visitor's browser type and version, and then load a specific version of the web page based on this information.
onload and onUnload events are also often used to handle cookies created when users enter or leave the page. For example, you can use a message box to ask the user for their name when they first enter the page. The name will be saved in the cookie. When the user enters this page again, you can use another message box to greet the user: "Welcome John Doe!".
onFocus, onBlur and onChange
onFocus, onBlur and onChange events are usually used together to validate the form.
The following is an example of using the onChange event. Once the user changes the content of the field, the checkEmail() function will be called.
onSubmit
onSubmit is used to validate all form fields before submitting the form.
The following is an example of using the onSubmit event. When the user clicks the confirm button in the form, the checkForm() function is called. If the field value is invalid, the submission will be cancelled. The return value of the checkForm() function is true or false. If the return value is true, submit the form, otherwise cancel the submission.