I wanted to: play the animation on my first click and stop it on my second click of the same button. Thanks.
Asked
Active
Viewed 51 times
-3
-
The key is in closures, wrap a function in an iffy that contains a "running" boolean state local variable, which your function uses to determine if it stops or runs with a simple if/then/else – Dellirium Jan 23 '19 at 11:33
-
That's not the scope of SO, but... You will have to save the "state" anywhere so you can check it in the click handler. – Andreas Jan 23 '19 at 11:34
-
onclick toggle two functions, one for animate one for stop animation. – Dhananjay Yadav Jan 23 '19 at 11:35
-
@InterviewSortout how do I tell the button to toggle on off? – Kartikeya Chauhan Jan 23 '19 at 11:38
2 Answers
0
Here is the simplest solution using closures, you should learn more on how closures work.
function generateMyStatefullFunction(){
var someState = false;
return function theActualFunctionThatDoesThings(){
if (someState){
console.log("State will be set to false, next click wont trigger this message");
}
someState = !someState;
}
}
var onClickHandler = generateMyStatefullFunction();
document.getElementById("button").addEventListener('click', onClickHandler);
<button id="button"> Fire every second click</button>

Dellirium
- 1,362
- 16
- 30
-
-
I've no clue why someone downvoted me, so I am as baffled as you are... Find more about closures here: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work they are a really important concept in javascript – Dellirium Jan 23 '19 at 11:46
-1
You can do like this
function performAction(event){
var button = event.currentTarget;
var action = button.innerHTML;
if(action == "Play"){
button.innerHTML = "Stop"
//play animation
} else {
button.innerHTML = "Play"
//stop animation
}
}
<div>
<button onclick="performAction(event)" >Play</button>
</div>

Serene Abraham Mathew
- 358
- 4
- 16
-
1While this undoubtedly works, it is relaying on external factors which is something you do not want to do, check my answer below for a more "good practice" approach. – Dellirium Jan 23 '19 at 11:48
-
@Dellirium - Your solution is nice , But this guy needs a simpler solution – Serene Abraham Mathew Jan 23 '19 at 11:58
-