About the addEventListener parameter, and the HTML DOM event propagation method (bubbling and capture)
addEventListener()
·AddEventListener() event listener, you can use removeEventListener() to remove the event listener.
· AddEventListener() attaches the event handler to the specified element without overwriting the existing event handler.
· AddEventListener() can be added to any DOM object, including window objects.
Syntax : element.addEventListener(event,function,useCapture);
Parameters :
- event: the type of event, click, mousedown, etc. There is no on prefix.
- function: the function to be executed when the event occurs
- useCapture: Specify whether to use event bubbling or event capture. Is a boolean value: the default is false, that is, event bubbling is used; when the value is true, event capture is used.
example
element.addEventListener("click", function(){
alert("Hello World!"); });
You can also write the function externally and use the function name as the second parameter:
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
It is allowed to add multiple events to the same element without overwriting the original events.
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Event bubbling and event capture
HTML DOM has two event propagation methods: event bubbling and event capture.
For example: if there is a p element in the div element, then the user clicks the p element, should the p element be processed first, or should the event of the div element be processed first?
- Event bubbling: first process internal element events, then trigger external elements; that is, process p element first, then process div element.
- Event capture: Process the event of the external element first, and then trigger the internal element. That is, the div element is processed first, and then the p element is processed.
Event removal removeEventListener()
element.removeEventListener("mousemove", myFunction);