Can this function be organized better?

It’s normally not suitable to replace document with other things. That is an indirection (referencing using a reference instead of the thing itself), and leads to too much confusion.

Using a variable at the start of the resetPage function is suitable though.

const body = document.querySelector("body");

That way you can just use body instead of document.querySelector(“body”)

In regard to the function name, it helps to ask what does the function do? It’s an event handler that triggers after the fade animation has ended. The animation end part is already taken care off by the event name of “animationend”, so the rest of what it does is explained by being a fade reset handler. Calling the function fadeResetHandler looks to be a most suitable name.

The removeEventListener that you’ve used there is poorly supported by some web browsers. Instead of adding and removing the event listener, it’s best to add the event listener only once, usually from an init function, and don’t fiddle with it afterwards. To achieve that the fadeResetHandler function cannot be inside of the resetPage function. That fadeResetHandler function needs to be moved out of that function, possibly just above the resetPage function. That way the addEventListener can be moved to the init function, and the fadeResetHandler function can still be accessed from there. That way the removeEventHandler statement can be removed, helping to make your code more reliable across different web browsers.

1 Like