Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  79] [ 2]  / answers: 1 / hits: 21425  / 7 Years ago, wed, august 16, 2017, 12:00:00

I have been trying to find a way to remove an event listener. I made a function that will add an event listener to a button but if the function runs again I want the event listener to be removed and added again. But instead it will just add another event listener and when I click on the button it will run the event listener function twice. Or even if I can just prevent it from adding a second event listener to the button would work too.



Here is the code





<button id=myId>My Button</button>



<script>



myFunction()
myFunction()

function myFunction() {
var el = document.getElementById('myId')

var listenerFn = function () {
console.log('My Message')
}

el.removeEventListener('click', listenerFn)

el.addEventListener('click', listenerFn)
}



</script>





Any tips would be most helpful.



UPDATE:



@FathiAlqadasi answer is the best so far for my issue. But I should of shown more of the code. the listener function is dynamic and can vary on what it does. Here is a another example of what I mean.



<button id=myId>My Button</button>



<script>

myFunctionA()
myFunctionA()



function myFunctionA() {
var el = document.getElementById('myId')
myFunctionB()
function myFunctionB() {
if (el.innerHTML === 'My Button') {
var listenerFn = function () {
console.log('My Message 1')
}

el.removeEventListener('click', listenerFn);

el.addEventListener('click', listenerFn);
}

else {
var listenerFn = function () {
console.log('My Message 2')
}

el.removeEventListener('click', listenerFn);

el.addEventListener('click', listenerFn);
}
}
}
</script>


UPDATE 2:



Thank you @ for the code. Here is the code in a neat codebox



<button id=myId>My Button</button>

<script>
var listenerFn;
myFunction();
myFunction()
function myFunction() {
var el = document.getElementById('myId')
el.removeEventListener('click', listenerFn);
listenerFn = function() {
console.log('My Message')
}
el.addEventListener('click', listenerFn, false);
}
</script>

More From » events

 Answers
25

In this example, we add and remove the listener in the same function as alternative to prevent redundant listeners.




function callbackFunction() {
console.log('Callback function was called.')
}

function addRemoveListener() {
let el = document.getElementById('btn-test')

el.removeEventListener('click', callbackFunction)
el.addEventListener('click', callbackFunction)
}

addRemoveListener()
addRemoveListener()

<button id=btn-test>Button</button>




[#56739] Monday, August 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;