Wolfram Research

Function Repository Resource:

OnOffToggle

Source Notebook

A checkbox-type control styled as a colored toggle slider

Contributed by: Jon McLoone  |  Jon McLoone

ResourceFunction["OnOffToggle"][Dynamic[arg]]

represents a toggle switch with setting arg.

ResourceFunction["OnOffToggle"][Dynamic[arg,fn]]

represents a toggle switch with setting arg and update function fn.

Details and Options

ResourceFunction["OnOffToggle"] accepts the following options:
"Interaction""Click"whether mouse click or mouse drag actions are required
"OffBackgroundColor"LightGraybackground color when False
"OffColor"Lighter[Red,0.2]toggle color when False
"OnBackgroundColor"LightGraybackground color when True
"OnColor"Lighter[Green]toggle color when True
FrameStyleNonestyle appled to the toggler frame
ImageSize40horizontal size of the toggler

Examples

Basic Examples (3) 

Create an interactive switch that can be toggled with a mouse click:

In[1]:=
x = False;
ResourceFunction["OnOffToggle"][Dynamic[x]]
Out[2]=

When the control variable is True, the switch moves to the right and changes color:

In[3]:=
y = True;
ResourceFunction["OnOffToggle"][Dynamic[y]]
Out[4]=

Two-argument Dynamic is supported:

In[5]:=
t = True;
ResourceFunction["OnOffToggle"][
 Dynamic[t, Function[{val, var}, var = Echo@val, {HoldAll}]]]
Out[6]=

Scope (1) 

OnOffToggle can be used everywhere that other Dynamic controls can be:

In[7]:=
Manipulate[{a, b, c},
 {a, ResourceFunction["OnOffToggle"][#] &},
 {b, ResourceFunction["OnOffToggle"][#] &},
 {{c, True}, ResourceFunction["OnOffToggle"][#] &}]
Out[7]=

Options (4) 

The toggle color and background color can be individually controlled for both the on and off states:

In[8]:=
x = False;
ResourceFunction["OnOffToggle"][Dynamic[x], "OffBackgroundColor" -> Lighter[Red, 0.5], "OffColor" -> Black, "OnBackgroundColor" -> Lighter[Green, 0.8], "OnColor" -> Gray]
Out[9]=
In[10]:=
y = True;
ResourceFunction["OnOffToggle"][Dynamic[y], "OffBackgroundColor" -> Lighter[Red, 0.5], "OffColor" -> Black, "OnBackgroundColor" -> Lighter[Green, 0.5], "OnColor" -> LightGray]
Out[11]=

A frame can also be styled:

In[12]:=
ResourceFunction["OnOffToggle"][Dynamic[y], FrameStyle -> Black]
Out[12]=

The controller size can be set with ImageSize:

In[13]:=
ResourceFunction["OnOffToggle"][Dynamic[y], ImageSize -> 80]
Out[13]=

The controller switches state with mouse clicks, but it can be set to require dragging between states. Any position right of center is treated as True:

In[14]:=
ResourceFunction["OnOffToggle"][Dynamic[z], "Interaction" -> "Drag"]
Out[14]=

Resource History

Related Resources

License Information