-3

I wanted to: play the animation on my first click and stop it on my second click of the same button. Thanks.

2 Answers2

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 seriously have no clue what closures are but thankks! – Kartikeya Chauhan Jan 23 '19 at 11:45
  • 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>