Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
How to change the addEventListener callback function in javascript

How do I change the function in addEventListener.

//how do I turn this
button.addEventListener('click', test)
//into this
button.addEventListener('click', test2)

I am okay with using js libraries. I have an idea that I can use removeEventListener and then add another event listener but I don't know how to add an eventListener in javascript.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

To switch EventListeners on the button, you would do exactly as you suggested

button.addEventListener("click", test)

button.removeEventListener("click", test)

button.addEventListener("click, test2)

An EventListener is essentially one of two things.

  1. A function that accepts an event object as an input parameter.
  2. An object that has a handleEvent function that accepts an event object as an input parameter.

For test2 to be an EventListener, it would just need to be one of those two things.

Option 1: As a function

function test2(event) {
    console.log(event)
}

button.addEventListener("click", test2)

Option 2: As an object with a handleEvent function

const test2 = {
    "handleEvent": (event) => {
        console.log(event)
    } 
}

button.addEventListener("click", test2)

The documentation to support this can be found here:

https://developer.mozilla.org/en-US/docs/Web/API/EventListener

about 4 years ago · Juan Pablo Isaza Relatório

0

This can be done with delegation, just assign each time the function to a variable, then call the variable from callback, like this:

let fn = () => {
  alert('1');
  fn = () => alert('2');
};

button.addEventListener('click', function () {
  fn.apply(this, arguments);
});
<button id="button">OK</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda