wololoo
wololoo

Reputation: 175

What is the correct way to override DOM event handlers?

If I have created a button and attached a click handler:

let btn = document.createElement("button");
btn.innerHTML = "Do Something";
btn.onclick = () => { doSomething(); };
document.body.appendChild(btn);

And later I want to re-use the button for something else, is this a safe way to override the event handler?

btn.innerHTML = "Do Something Else";
btn.onclick = () => { doSomethingElse(); }

I've seen some examples that set btn.onclick = null; before attaching a new handler. Also some examples with addEventListener() / removeEventListener(). Is there a difference between these methods? Can I be introducing memory leaks with any of these?

Upvotes: 1

Views: 721

Answers (1)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8118

In order to allow multiple handlers to be installed for the same event on a given object, you can call its addEventListener() method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its removeEventListener() function.

After removing the previous event handler, you can again attach a new event handler to the same element. This way there wouldn't be any memory leaks as well.

Code Demo:

let btn = document.createElement("button");
btn.innerHTML = "Do Something";
element.addEventListener("click", doSomething, true)
document.body.appendChild(btn);

           ...
btn.removeEventListener("click", doSomething, true);  

// Third argument must be same as in earlier case. true in this case.

btn.addEventListener("click",doSomethingThingElse};

Upvotes: 1

Related Questions