Basically what I'm trying to accomplish is removing an event handler from a button element (with removeEventListener method) and replacing it with another on first click (with addEventListener method), and so when clicked from time to time again, it keeps switching back and forth from its original event handler function to its alternate.
Theoretically, the function counter()
outputs all numbers up from 0 indefinitely in a paragraph element onclick until the user clicks the button element again (count ceases with function altFunc()
. And to continue the count after ceasing it, the user simply clicks the button element again, and can stop and continue as many times as the user pleases.
What I've tried:
var a = 0;
var b = setInterval(execute_counter, 1000);
function add() {
return a += 1;
}
function counter() {
document.getElementsByTagName('BUTTON')[0].removeEventListener('click', counter);
document.getElementsByTagName('BUTTON')[0].addEventListener('click', altFunc);
setInterval(execute_counter, 1000);
function execute_counter() {
document.getElementsByTagName('P')[0].innerHTML = add();
}
}
function altFunc() {
document.getElementsByTagName('BUTTON')[0].removeEventListener('click', altFunc);
document.getElementsByTagName('BUTTON')[0].addEventListener('click', counter);
clearInterval(b);
}
//This was my first attempt. Output is just an endless loop.
//Second attempt follows utilizing a switch statement belonging to function changeOver() containing the remove and add eventListener methods:
var a = 0;
var b = setInterval(execute_counter, 1000);
function add() {
return a += 1;
}
function counter() {
setInterval(execute_counter, 1000);
function execute_counter() {
document.getElementsByTagName('P')[0].innerHTML = add();
changeOver();
}
}
function changeOver() {
switch(counter() || altFunc()) {
case counter():
document.getElementsByTagName('BUTTON')[0].removeEventListener('click', counter);
document.getElementsByTagName('BUTTON')[0].addEventListener('click', altFunc);
break;
case altFunc():
document.getElementsByTagName('BUTTON')[0].removeEventListener('click', altFunc);
document.getElementsByTagName('BUTTON')[0].addEventListener('click', counter);
}
}
function altFunc() {
clearInterval(b);
}
//Second attempt's output also is an endless loop.
I think that the remove and add event listeners are working, I am not however understanding the logic behind all of it. I'd appreciate answers in helping me understand it as well as resolving this issue. Thank y'all.
...HTML:
<button type="button" onclick="counter()">counter/altFunc</button>
<p></p>