Creating an On/Off button

Hi im wondering how to create a button that performs two separate actions depending on a state, like an on/off switch. For instance, say ButtonA turns a box blue when clicked and released. Clicking on ButtonA again turns the box green. Clicking on the box a third time returns the box to blue and so on. Any thoughts on this? Is it an if/then?

Hi Adam,

It sounds like you want to have a button that functions like a toggle (click once to have something happen and click again to have something else happen). You can find some sample code for toggles in the API here that you could put in an onClick event handler .

Hi Adam,

You could also use a Checkbox. Although it doesn’t have the classic appearance of a toggle switch, it basically behaves like one.

Please feel free to post a request in the Feature Requests forum. An “official” toggle switch would be nice.

Yisrael

@Yisrael could you point me to some sample code for the checkbox? Id really appreciate it

Hey Adam,

Look at the checked property to see how to toggle the checkbox on and off. You can find other use cases and sample code in the rest of the $w.Checkbox API documentation .

Yisrael

I’m trying to do something similar to what this post is about. Can you tell me why this doesn’t work:

export function switch2_change(event) {
$w(“#switch1”).checked = false ;
}

Note that #switch1 is true by default…when i load the page and click #switch2 nothing happens to #switch1 when I believe it should shut off, or at least that is what I would like it to do

Hi,
Is the switch connected to a dataset?
If not can you please share a link to your site and specify the name of the page so we can inspect?
Roi.

I actually figured it out, but I’m not doing it within the scope of export function switch2_change(event). That being said, could you briefly comment on when/where you would call the export function switch2_change(event) within the page code? Or maybe it’s intended to be called elsewhere? Right now, this is what I’m doing on the page code

$w.onReady( function () {

$w('#switch2').onClick((event) => { 
  // Do stuff here 
 }) 

})

Basically I created my own “onClick” event. Again, I don’t see how/when/where/why I would use export function switch2_change(event)? I should note that this function was predefined/created when I added an “onClick” event from the “Developer Tools Properties Panel”.