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>
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>