Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the Event Listener on a Button programatically

I have a Button which is registered with a onclick event as shown

<Input type="Button" name="Register" Value="Register" onclick="CallMe();"/>

Is it possible to programatically remove or deregister the onclick event on this Button?

like image 769
Kiran Avatar asked Apr 03 '11 11:04

Kiran


People also ask

How do I remove event listener from click?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

How do I get rid of event listener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

How do I remove all event listeners from an element?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Does removing an element remove event listeners?

In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.


2 Answers

You could set the onclick attribute to null.

var el = document.getElementById('inputId');
el.onclick = null;

or better just remove the attribute altogether with the removeAttribute() docs method of the element.

var el = document.getElementById('inputId');
el.removeAttribute('onclick');

you will need to add an id to the element though for this..

example code at http://jsfiddle.net/gaby/PBjtZ/

like image 145
Gabriele Petrioli Avatar answered Oct 26 '22 21:10

Gabriele Petrioli


document.getElementsByName("Register")[0].onclick = "" 

or

document.getElementsByName("Register")[0].removeAttribute("onclick")

Make sure to place this in a JS tag at the end of your document. So the DOM is available when this script is running.

the first example gets all elements with the name "Register" in your dom and returns the first, then it finds and sets the onclick attribute to an empty string. (could be null to)

the second example does the same, but removes the attribute "onclick".

Be careful if you have more then one element with the name "Register" you should do it like Gaby aka G. Petrioli told you to.

like image 45
meo Avatar answered Oct 26 '22 21:10

meo