Creating a button to toggle between two States

Greetings Im trying to toggle between two States “Day” and “Night” when pressing a button, but im struggling with the code. So far it switches to the “Night” State okay but pressing the button again does nothing.

My code looks like this:

var DayNight_Day = symbol.controllers.DayNight.elements.Day;
var DayNight_Night = symbol.controllers.DayNight.elements.Night;

parent.on(“pointerdown”, (e) => {

if (DayNight_Day){
    DayNight_Night.activate();
}
else {
    DayNight_Day.activate();
}

});

,Regards thank you for any help

Greetings I figured it out funny enough, hopefully this will help others looking for a similar solution, im still relatively new to programing and am by no means experienced in it.

The solution.
I added another variable for the changing over for the "day/night"states called DaySwitch "var DaySwitch = True "

CODE:

var DayNight_Day = symbol.controllers.DayNight.elements.Day;
var DayNight_Night = symbol.controllers.DayNight.elements.Night;

var DaySwitch=true;

parent.on(“pointerdown”, (e) => {

if(DaySwitch){
DayNight_Night.activate();
DaySwitch=false;
}
else{
DayNight_Day.activate();
DaySwitch=true;
}

});

Hope this helps anyone. :slight_smile:

Well done for figuring it out - the new variable is a good solution.

Javascript has a concept called “truthyness”, and objects (such as DayNight_Day) always evaluate to true if they refer to an actual object, rather than “null”.

What you were trying to say in the first code block was if DayNight_Day is active, then do something. Controllers have an “activeElement” function, so you can actually write that test like this:

var DayNight = symbol.controllers.DayNight;
var DayNight_Day = symbol.controllers.DayNight.elements.Day;
var DayNight_Night = symbol.controllers.DayNight.elements.Night;

parent.on("pointerdown", (e) => {

if (DayNight.activeElement() === DayNight_Day){
    DayNight_Night.activate();
}
else {
    DayNight_Day.activate();
}
});

Personally I prefer to use separate variables to keep track of stuff in my code but that’s mainly down to personal preference.

3 Likes

Thank you!

I did not know about the ".activeElement() " function, I figured something was wrong with my “if” statement, thank you for explaining in more detail what was going on appreciate it.

Here is the scripting reference for the activeElement function - https://docs.zap.works/studio/scripting/reference/controller/functions/activeelement/