Skip to content Skip to sidebar Skip to footer

Extract Function From Addeventlistener

In a nutshell, I have 3 divs that will have their bg colour randomly changed when clicked. They can only be clicked once, hence the removeEventListener. Am I just trying to over-co

Solution 1:

Since the body of the functions are different, I don't think there's a way to have a singe outside function that removeEventListener can be called for. But there is an easy way to simplify things: use { once: true } so that the listener can only be called once, no need for removeEventListener at all.

// the below line can be made less repetitive
// by using querySelectorAll instead, if possible
for (const door of [doorLeft, doorMiddle, doorRight]) {
  door.addEventListener(
    'click',
    () => randomChooseColor(door),
    { once: true }
  );
}

Post a Comment for "Extract Function From Addeventlistener"