Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to prevent a function from continuing to be called after removing the onclick attribute from an element is to store the function reference in a variable and check for its existence before calling it.

For example, you can define a function and store its reference in a variable like this:

function myFunction() {
  // do something
}

var myFunctionRef = myFunction;

Then you can assign the function to an element's onclick attribute like this:

document.getElementById("myButton").onclick = myFunctionRef;

To remove the onclick attribute, you can set it to null:

document.getElementById("myButton").onclick = null;

And to prevent the function from being called if the onclick attribute has been removed, you can check if the function reference still exists before calling it:

if (myFunctionRef) {
  myFunctionRef();
}

This way, if the onclick attribute has been removed and the function reference is null, the function won't be called.