1

i want to configure two different actions on a button depending on the click. For the first time click , i want to call a function F1() and on all other time i want call another function F2().

I am new to javascript, and i am looking for a variable that can store the value like a flag. I tried it but the values are not persisting.

<script>
  var fflag=1;

  if(fflag!=2){
    F1();//do an action
    fflag =  2;
 }
 else{
    F2();//do another action
 }
</script>

2 Answers 2

3

Use a boolean instead:

var clicked = false;

function onButtonClick(){
    if(clicked){ // If this button has been clicked before,
        F2();   // Execute F2
    } else {   // If this button hasn't been clicked before,
        clicked = true; // Change the boolean.
        F1(); // Execute F1
    }
}

A shorter alternative:

var clicked = false;
function onButtonClick(){
    (clicked ? F2 : F1)();
    clicked = true;
}

(This uses the ternary operator).

Sign up to request clarification or add additional context in comments.

6 Comments

What's with the downvote? How on earth is this answer incorrect?
thank you. eveytime iam getting F2() called first.function onButtonClick(){ if(clicked){ alert("f1 called"); F1(); } else { clicked = true; alert("f2 called"); F2(); } }
Look at my code, you switched F1 and F2. In my code, F2 is in the if, not in the else.
switching was not the problem, there was a typo in my code. Thank you this solved the issue
& i didnt downvote ur answer, just started stackoverflow and have only gained upvote privilege i think
|
-2

You need to set the fflag variable outside of the function that is using it, this will make it global (or at least outside the scope of the function) and its value will persist between function calls.

<script>
var fflag = 1;

function myClick() {
  if(fflag!=2){
    F1();//do an action
    fflag =  2;
  }
  else{
    F2();//do another action
  }
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.