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
CodePudding user response:
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();">
CodePudding user response:
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);
CodePudding user response:
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);