-1

There is a webpage that is loading an event listener for click that I want to remove permanently. I am not setting the function myself because it is loaded by the site. I just need to remove the event listener.

I know both the event and the function.

Why will this event listener not remove?

  • Possible duplicate: https://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery – Jeroen Jun 22 '18 at 09:23
  • 3
    Possible duplicate of [Remove event listener in JavaScript](https://stackoverflow.com/questions/8841138/remove-event-listener-in-javascript) – JTC Jun 22 '18 at 09:25
  • 1
    "I know both the event and the function." what do you mean by "know the function"? Do you have access to it? – Yury Tarabanko Jun 22 '18 at 09:35
  • @YuryTarabanko I am aware that the event is click and that the function is Zt. However, I can not make changes to the site. – user9977452 Jun 22 '18 at 09:42
  • If it’s okay to remove _all_ event listeners of some container element, then create a new element of the same type and append it after the container. Append all child nodes of the first container onto the second one, then remove the old container. This will leave all the functionality within the container intact, but will remove the event listeners of the container itself. Here’s a [proof of concept](https://jsfiddle.net/cjwbvyzg/10/) of how this might work. – Sebastian Simon Jun 22 '18 at 09:55

1 Answers1

0

If the element has an onclick attribute, do this simply by removing the onclick attribute. See the code below:

function myFunction() {
    document.getElementById( 'element' ).removeAttribute( 'onclick' )
}
<a id="element" href="https://stackoverflow.com" onclick="alert( 'Stack Overflow' ); return false">Click here for alert.</a>
<p>Click the button below to remove event listener from above link.</p>
<button onclick="myFunction()">Remove Event Listener</button>

But, if the element does not have an onclick attribute, you must have access to the click function and use removeEventListener() Method. See the code snippet below:

document.getElementById( 'element' ).addEventListener( 'click', Zt )

function Zt( e ) {
  e.preventDefault();
  alert( 'Stack Overflow' )
}

document.getElementById( 'button' ).addEventListener( 'click', function() {
  document.getElementById( 'element' ).removeEventListener( 'click', Zt )
} )
<a id="element" href="https://stackoverflow.com">Click here for alert.</a>
<p>Click the button below to remove event listener from above link.</p>
<button id="button">Remove Event Listener</button>
Kavian K.
  • 1,212
  • 1
  • 7
  • 11