Documento HTML DOM addEventListener()
Exemplos
Adicione um evento de clique ao documento:
document.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Sintaxe mais simples:
document.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Mais exemplos abaixo.
Definição e uso
O addEventListener()
método anexa um manipulador de eventos ao documento.
Veja também:
O tutorial do HTML DOM EventListener
O método removeEventListener() do documento
Sintaxe
document.addEventListener(event, function, useCapture)
Parâmetros
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.
|
Valor de retorno
NONE |
Mais exemplos
Você pode adicionar vários ouvintes de eventos ao documento:
document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
Você pode adicionar diferentes tipos de eventos:
document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
Ao passar parâmetros, use uma "função anônima" para chamar uma função com os parâmetros:
document.addEventListener("click", function() {
myFunction(p1, p2);
});
Altere a cor de fundo do documento:
document.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Usando o método removeEventListener():
// Add an event listener
document.addEventListener("mousemove", myFunction);
// Remove event listener
document.removeEventListener("mousemove", myFunction);
Suporte ao navegador
document.addEventListener
é um recurso DOM Nível 2 (2001).
É totalmente suportado em todos os navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |