yollen yollen - 5 months ago 10
Javascript Question

Use one button instead of two for changing string

I have a variable and I need it to switch its string back and fourth each time the user presses a button. I'm using two functions to do that, one to change it to 'short' and one to 'long'. The default setting on my website is 'short'. The problem is that I don't want it to use two buttons since it would take away space. I need one function that will change it from a to b and from b to a.

var sl = "short";
function short() {
sl = "short";
}
function long() {
sl = "long";
}

Answer

This should fit what you want to do. Its untested, but it should work.

var sl = "short";
var on = 1;

if (on == 1) { 
 on = 0;
 console.log("Short became long");
 sl = "long";
 }
else if (on == 0) {
 on = 1;
 console.log("Long became short");
 sl = "short";
 } 

We have an integer variable which represents the 'default on' state (you can use a boolean instead of an integer if you want) When the code is ran, if 'on' is 1, then it sets it to 0 and executes the 'off' code. If the variable 'on' is 0, it will set it to 1 and execute the 'on' code. You can put this inside a function and call the function to execute on/off code.