1

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.

5
  • Have you tried your idea? Commented Mar 30, 2022 at 20:39
  • I don't know how to add an evenlistener with javascript only, without having to write the code, so the javascript will generate itself basically Commented Mar 30, 2022 at 20:40
  • You think it's going to code itself? Commented Mar 30, 2022 at 20:41
  • no so how can I make a function change the addEventListener function, I'm trying to do what is in the code block Commented Mar 30, 2022 at 20:43
  • Make a function that accepts the element as one parameter and the listener type as another. Then remove any previous listener before adding the new one. Commented Mar 30, 2022 at 20:47

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.