0

I am trying to change the boolean value from true to false and false to true whenever the button is clicked however the value is changing within the function but when I console the value outside the function it is giving the default value that I set during the variable declaration`

var bool = 0; 
switchCameraButton.addEventListener('click', function() {
                
                camera.switch();
                if(bool == 0){
                    bool = 1;
                }else{
                    bool = 0;
                }
                console.log(bool);
            });

console.log(bool);

`

I was trying to change the boolean value when ever the button is clicked but the value is not changing i mean it is changing within the onclick function but not outside the function

1
  • How do you know the value is not changing outside the click function? The console.log fires before the button is clicked. What problem is it that you are hoping to overcome using a global variable? Is it to do with the camera.switch() somehow? Commented Jan 2, 2023 at 10:43

3 Answers 3

1

you can use this script to change the value of a variable on click event

var bool_val=false;
function changeVal(){
  bool_val=!bool_val;
   console.log(bool_val);
}
<input type="button" value="change" onclick="changeVal();">

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

1 Comment

Perfect answer except than prefer to use an eventListener in place of onclick... mybutton.addEventListener("click",onClickButton); +1 anyway for @ZulqarnainJalil
0

a possible solution is using localStorage to save your bool value here is an example

// Your boolean is whatever you have in the localStorage if the localStorage is empty the default value will be 0
let bool = localStorage.getItem('myBoolValue') | 0; 

switchCameraButton.addEventListener('click', function() {             
    camera.switch();
    
    // this is the logical not operator it transform your bool variable from 0 to 1 and vise versa
    bool = !bool;
    
    // save your bool in localStorage, by using the + am just turning true or false to 1 or 0
    localStorage.setItem('myBoolValue', +bool);
 });

console.log(bool);

Comments

0

I think you need to make sure that the bool variable is declared outside the onclick function. This way, the value of bool will be accessible outside the function, and will be updated when button is clicked.

For example:

var bool = 0;

switchCameraButton.addEventListener('click', function() {
    camera.switch();
    if(bool == 0){
        bool = 1;
    }else{
        bool = 0;
    }
});

console.log(bool);

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.