Search code examples
javascriptjquerydomweb-frontendclient-side-scripting

How to activate and disable jQuery 'click' events on an HTML element


I have a button with two click events attached to it. I am having trouble disabling one 'click' event while keeping on another.

need to have functionality so on the first click will alert("first was clicked"), on the second click will alert("second was clicked"), on the third click will alert("first was clicked"), on fourth click will alert("second was clicked") and so on...

<button id="clickable">

$('#clickable').on('click', function first_click () {

    alert("first was clicked");

$("#clickable").off('click', first_click);

    $('#clickable').on('click', function second_click () {

       alert("second was clicked");

  // need to have functionality so on the first click will alert("first was clicked"),  on the second click will alert("second was clicked"), on the third click will alert("first was clicked"), on fourth click will alert("second was clicked") and so on...    

     });

});

Solution

  • var checkFlag = true;
    function clicked(){
      if(checkFlag == true){
      alert("first clicked");
      }else{
      alert("Second clicked");
      }
      checkFlag = !checkFlag;
    }
    <button onClick="clicked();">Click</button>

    use boolean flag to check