To get JavaScript to respond to a user's actions, we first bind the event handler to the DOM element. The so-called event handler function is the function that handles the user operation, and different operations correspond to different names.
In JavaScript, there are three common ways to bind events:
- Bind directly in the DOM element;
- Binding in JavaScript code;
- Binds the event listener function.
I. Binding directly in the DOM element
The DOM elements here can be understood as HTML tags. JavaScript supports the direct binding of events in tags, with the following syntax:
onxxx= "JavaScript Code"
which
OnXXX is the event name. For example, mouse click event onclick, mouse double-click event ondouble, mouse move into event onmouseover, mouse move out event onmouseout, etc.
JavaScript code is the JavaScript that handles events, typically functions.
For example, if you click a button, the code that pops up the warning box has the following two notation.
1. Native functions
- <input onclick="alert (' Thank you support ')" type="button" Value="Tap me, pop Up warning box" />
2. Custom Functions
- <input onclick="Myalert ()" Type="button" Value="Tap me, pop Up warning box" />
- <script type="Text/javascript">
- function Myalert(){
- Alert("Thank you for your support");
- }
- </script>
Two. Binding in JavaScript code
Binding events in JavaScript code (that is, in <script> tags) separates JavaScript code from HTML tags, makes the document structurally clear and easy to manage and develop.
The syntax for binding an event in JavaScript code is:
Elementobject.onxxx=function () {
Event handling code
}
which
- Elementobject is a DOM object, which is a DOM element.
- OnXXX is the event name.
For example, to bind an event to a button that id= "demo", display its Type property:
- <input id="Demo" type="button" Value="Click me, Show Type property" />
- <script type="Text/javascript">
- Document. getElementById("Demo"). onclick=function(){
- Alert(this. GetAttribute("type")); //This refers to the HTML element of the current event, which is the <div> tag
- }
- </script>
Three. Binding Event listener
Another way to bind an event is to use AddEventListener () or attachevent () to bind the event listener function.
AddEventListener () function syntax:
Elementobject.addeventlistener (eventname,handle,usecapture);
Common methods of event binding in JavaScript