HTML DOM dokument addEventListener()
Příklady
Přidejte do dokumentu událost kliknutí:
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Jednodušší syntaxe:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Další příklady níže.
Definice a použití
Metoda addEventListener()
připojí k dokumentu obslužnou rutinu události.
Viz také:
Výukový program HTML DOM EventListener
Metoda Document removeEventListener().
Syntax
document.addEventListener(event, function, useCapture)
Parametry
Parameter | Description |
event | Required. The event name. Do not use the "on" prefix. For example, use "click" instead of "onclick". HTML DOM events are listed in Complete HTML DOM Event Object Reference. |
function | Required. The function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object. |
useCapture |
Optional. A boolean. Specifies if the event should be executed in the capturing or in the bubbling phase (default). true - The event handler is executed in the capturing phase.false - The event handler is executed in the bubbling phase.
|
Návratová hodnota
NONE |
Další příklady
Do dokumentu můžete přidat mnoho posluchačů událostí:
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
Můžete přidat různé typy událostí:
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
Při předávání parametrů použijte "anonymní funkci" k volání funkce s parametry:
document.addEventListener("click", function() {
myFunction(p1, p2);
});
Změňte barvu pozadí dokumentu:
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Pomocí metody removeEventListener():
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
Podpora prohlížeče
document.addEventListener
je funkce DOM úrovně 2 (2001).
Je plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |