({{, (RefLink[DynamicModule, paclet:ref/DynamicModule])[{x,y,…},expr]
represents an object which maintains the same local instance of the symbols x, y, … in the course of all evaluations of (RefLink[Dynamic, paclet:ref/Dynamic]) objects in expr. Symbols specified in a (RefLink[DynamicModule, paclet:ref/DynamicModule]) will by default have their values maintained even across Wolfram System sessions. }, {, (RefLink[DynamicModule, paclet:ref/DynamicModule])[{x=(Subscript[x, 0]),y=(Subscript[y, 0]),…},expr]
specifies initial values for x, y, …. }})

OpenersNotesSection(Spacer1)Details and Options

(RefLink[DynamicModule, paclet:ref/DynamicModule]) first gives unique names to local variables in expr, just like (RefLink[Module, paclet:ref/Module]), then evaluates the resulting expression, and then returns a version of this wrapped in (RefLink[DynamicModule, paclet:ref/DynamicModule]).

In a notebook, this returned version will often be displayed in an output cell. An example is the output from (RefLink[Manipulate, paclet:ref/Manipulate]).

If interactive changing or editing of (RefLink[Dynamic, paclet:ref/Dynamic]) objects within the displayed form of a (RefLink[DynamicModule, paclet:ref/DynamicModule]) results in changes in any values for local variables, then the (RefLink[DynamicModule, paclet:ref/DynamicModule]) object is modified to reflect these.

Values of local variables in a (RefLink[DynamicModule, paclet:ref/DynamicModule]) are by default automatically saved when a notebook containing the (RefLink[DynamicModule, paclet:ref/DynamicModule]) is saved, so that these values in effect persist across sessions of the Wolfram System.

If you make a copy of a piece of a notebook that contains a (RefLink[DynamicModule, paclet:ref/DynamicModule]) object, the local variables in the copy will be independent of the local variables in the original, though they will start with the same values.

The following options can be given:

When (RefLink[DynamicModule, paclet:ref/DynamicModule]) is first evaluated, initial assignments for local variables are made during the evaluation. Any setting for the (RefLink[Initialization, paclet:ref/Initialization]) option is evaluated only when the output of (RefLink[DynamicModule, paclet:ref/DynamicModule]) is displayed.

When a (RefLink[DynamicModule, paclet:ref/DynamicModule]) object is displayed for the first time in a particular notebook, saved values for local variables are restored, and then any setting for the (RefLink[Initialization, paclet:ref/Initialization]) option is evaluated.

All values of local variables are saved, except for those included in the (RefLink[UnsavedVariables, paclet:ref/UnsavedVariables]) list. Ordinary values of symbols are saved in the first argument of the (RefLink[DynamicModule, paclet:ref/DynamicModule]); other values are saved in the setting for the (RefLink[DynamicModuleValues, paclet:ref/DynamicModuleValues]) option.

(RefLink[DynamicModule, paclet:ref/DynamicModule]) has attribute (RefLink[HoldAll, paclet:ref/HoldAll]).

(RefLink[DynamicModule, paclet:ref/DynamicModule]) constructs can be nested in any way, with inner variables being renamed if necessary.

(RefLink[DynamicModule, paclet:ref/DynamicModule]) is a scoping construct that implements lexical scoping.

OpenersPrimaryExamplesSection(Spacer1)Examples  (29)

OpenersExampleSection0(Spacer1)Basic Examples  (1)

Create a (RefLink[Slider, paclet:ref/Slider]) with a dynamically updating localized variable:

DynamicModule[{x},{Slider[Dynamic[x]],Dynamic[x]}]

Copy and paste the output above to get a standalone object:

OpenersExampleSection1(Spacer1)Scope  (6)

OpenersExampleSubsection0(Spacer1)DynamicModule Variables  (3)

Use (RefLink[DynamicModule, paclet:ref/DynamicModule]) to localize variables and prevent conflicts with their global counterparts:

{Slider[Dynamic[x]],Dynamic[x]}

DynamicModule[{x},{Slider[Dynamic[x]],Dynamic[x]}]

Local variables are unique to the generated output:

{Slider[Dynamic[x]],Dynamic[x]}

%

DynamicModule[{x},{Slider[Dynamic[x]],Dynamic[x]}]

%

Assign initial values to local variables, just like (RefLink[Module, paclet:ref/Module]):

DynamicModule[{a=3,b=2,c=1},{a,b,c}.x^Range[3]]

Define a function as a local variable:

DynamicModule[{f,p},f[g_]:=Graphics[g,ImageSize->Tiny];{SetterBar[Dynamic[p],{Disk[]->Disk,Rectangle[]->Rectangle}],Dynamic[f[p]]}]

OpenersExampleSubsection1(Spacer1)DynamicModule State  (3)

Use (RefLink[DynamicModule, paclet:ref/DynamicModule]) to save the displayed state across different Wolfram System sessions:

DynamicModule[{x=1},Slider[Dynamic[x]]]

InputForm[ToBoxes[%]]

(RefLink[Module, paclet:ref/Module]) only gives unique states in the current Wolfram System session:

Module[{x=1},Slider[Dynamic[x]]]

InputForm[ToBoxes[%]]

Use (RefLink[Initialization, paclet:ref/Initialization]) to evaluate expressions before displaying the contents:

DynamicModule[{x},Slider[Dynamic[x]],Initialization:>(SelectionMove[EvaluationNotebook[],All,EvaluationCell];SetOptions[NotebookSelection[],CellFrame->1,CellFrameColor->Hue[x]])]

(RefLink[Initialization, paclet:ref/Initialization]) is evaluated after the local variable assignments:

DynamicModule[{a=2},Dynamic@a,Initialization:>(a=1)]

OpenersExampleSection2(Spacer1)Generalizations & Extensions  (1)

Define an arbitrary number of local variables by assigning down values to a variable:

displayInputFields[numInputFields_]:=DynamicModule[{values},
Do[values[i]=i,{i,numInputFields}];
InputField[Dynamic[values[#]]]&/@Range[numInputFields]]

displayInputFields[5]

OpenersExampleSection3(Spacer1)Options  (14)

OpenersExampleSubsection2(Spacer1)BaseStyle  (1)

Set the base style:

DynamicModule[{x="this is some text"},Dynamic[x],BaseStyle->{FontSize->8}]

OpenersExampleSubsection3(Spacer1)Deinitialization  (1)

Specify expressions to be evaluated when output is no longer displayed:

CreateDialog[DynamicModule[{c},ColorSlider[Dynamic[c]],Initialization:>(c=Pink),Deinitialization:>(CreateDialog[Graphics[{c,Disk[]}]])]];

OpenersExampleSubsection4(Spacer1)DynamicModuleValues  (1)

Function definitions of local symbols are automatically inserted into (RefLink[DynamicModuleValues, paclet:ref/DynamicModuleValues]):

InputForm[DynamicModule[{c},c[x_]:={x};c[1]]]

OpenersExampleSubsection5(Spacer1)InheritScope  (1)

Create a dialog box with a (RefLink[DynamicModule, paclet:ref/DynamicModule]) that inherits variables from a parent (RefLink[DynamicModule, paclet:ref/DynamicModule]):

DynamicModule[{a=1},{Dynamic[a],Button["dialog",CreateDialog[DynamicModule[{},Button["a++",a++],InheritScope->True]]]}]

OpenersExampleSubsection6(Spacer1)Initialization  (4)

By default, external definitions are lost between kernel sessions:

f[x_]:={x}

DynamicModule[{c},{Slider[Dynamic[c]],Dynamic[f[c]]}]

Use (RefLink[Initialization, paclet:ref/Initialization]) to save evaluations necessary for the content:

DynamicModule[{c},{Slider[Dynamic[c]],Dynamic[g[c]]},Initialization:>(g[x_]:={x})]

Local variables can also be initialized:

DynamicModule[{c=0.2,g},
{Slider[Dynamic[c]],Dynamic[g[c]]},Initialization:>(g[x_]:={x})]

The initialization only runs if the output is displayed:

DynamicModule[{},1,Initialization:>(x=2)];DynamicModule[{},2,Initialization:>(y=3)]

The first (RefLink[DynamicModule, paclet:ref/DynamicModule]) was suppressed by the semicolon, so it never ran its assignment:

{x,y}

OpenersExampleSubsection7(Spacer1)SaveDefinitions  (2)

By default, external definitions are lost between kernel sessions:

f[x_]:=x

DynamicModule[{u=5},Dynamic[f[u]]]

By setting (RefLink[SaveDefinitions, paclet:ref/SaveDefinitions]) to (RefLink[True, paclet:ref/True]), the external definitions are saved with the output:

f[x_]:=x

DynamicModule[{u=5},Dynamic[f[u]],SaveDefinitions->True]

OpenersExampleSubsection8(Spacer1)SynchronousInitialization  (2)

By default, the initializations are evaluated before the output is displayed (synchronously):

DynamicModule[{c=0.2,g},{Slider[Dynamic[c]],Dynamic[g[c]]},Initialization:>(Pause[2];g[x_]:={x})]

Force the output to display while the initializations are evaluated asynchronously:

DynamicModule[{c=0.2},{Slider[Dynamic[c]],Dynamic[g[c]]},Initialization:>(Pause[2];g[x_]:={x}),SynchronousInitialization->False]

OpenersExampleSubsection9(Spacer1)UndoTrackedVariables  (1)

Create an interface that responds to the Undo menu command:

DynamicModule[{a=1},{Button["increment",a++],Dynamic[a]},UndoTrackedVariables:>{a}]

OpenersExampleSubsection10(Spacer1)UnsavedVariables  (1)

Specify symbols whose state should not be saved:

dm=DynamicModule[{x,y},Column@{Slider[Dynamic[x]],Slider[Dynamic[y]],Dynamic[{x,y}]},UnsavedVariables->{y}];

Evaluate the following and move the two sliders, then click Close:

nb=DialogInput[{dm,Button["Close",DialogReturn[NotebookGet[]]]}];

Evaluate the following and note that the second slider does not remember its previous state:

nb=DialogInput[nb];

OpenersExampleSection4(Spacer1)Applications  (3)

Construct a dynamic calculating interface:

DynamicModule[{a=0,b=0},Deploy[Style[Panel[Grid[Transpose[{{Style["input a number",Red],Style["input another number",Red],"here is their sum","their difference","their product"},{InputField[Dynamic[a],Number],InputField[Dynamic[b],Number],InputField[Dynamic[a+b],Enabled->False],InputField[Dynamic[a-b],Enabled->False],InputField[Dynamic[a b],Enabled->False]}}],Alignment->Right],ImageMargins->10],DefaultOptions->{InputField->{ContinuousAction->True,FieldSize->{{5,30},{1,Infinity}}}}]]]

Interactive curve fit plot:

DynamicModule[{pts={{0,0},{1,1},{2,0},{3,2}}},LocatorPane[Dynamic[pts],Dynamic[Plot[InterpolatingPolynomial[pts,x],{x,0,3},PlotRange->3]]]]

An angular slider with range (-∞, ∞):

angularSlider[Dynamic[angle_]]:=DynamicModule[{p={1,0},angleCalc},LocatorPane[Dynamic[p,(angleCalc@@Normalize/@{#,p})&],Graphics[{Circle[],Arrowheads[0.15],Arrow[Dynamic[{{0,0},p}]]},ImageSize->Tiny],Appearance->None],Initialization:>(angle=0;angleCalc[newp_,oldp_]:=(angle=angle+ArcCos[newp.oldp]Sign[Cross[newp].(newp-oldp)];p={Cos[angle],Sin[angle]}))]

Connect the slider to a dynamic variable:

{angularSlider[Dynamic[θ]],Dynamic[θ]}

Demonstrate a sinusoidal relationship:

DynamicModule[{θ=0},Grid[{{angularSlider[Dynamic[θ]],Plot[Sin[x],{x,-10,10},Epilog->{PointSize[Medium],Dynamic@Point[{θ,Sin[θ]}]}]},{ParametricPlot[{Cos[y],y},{y,-10,10},AspectRatio->2,Epilog->{PointSize[Medium],Dynamic@Point[{Cos[θ],θ}]}],Dynamic[θ]}}]]

Use (RefLink[PolarPlot, paclet:ref/PolarPlot]) to demonstrate a spiral curve:

DynamicModule[{θ=0},Grid[{{angularSlider[Dynamic[θ]],Dynamic@PolarPlot[t,{t,-Pi,θ},ImageSize->Tiny]}}]]

OpenersExampleSection5(Spacer1)Properties & Relations  (2)

(RefLink[DynamicModule, paclet:ref/DynamicModule]) and (RefLink[Module, paclet:ref/Module]) are fundamentally different although they seem similar:

DynamicModule[{x},{x,Slider[Dynamic[x]],Dynamic[x]}]

%

In this case both sliders will move, and will not work without evaluation when reopened:

Module[{x},{x,Slider[Dynamic[x]],Dynamic[x]}]

%

(RefLink[Manipulate, paclet:ref/Manipulate]) relies on (RefLink[DynamicModule, paclet:ref/DynamicModule]) to create the output:

Manipulate[x,{x,0,1}]

DynamicModule[{x},{Slider[Dynamic[x]],Dynamic[x]}]

OpenersExampleSection6(Spacer1)Neat Examples  (2)

Independent state sliders:

Expand[(DynamicModule[{x},Slider2D[Dynamic[x]]]+1)^3]

Click in the framed area to see bouncing balls:

Framed@DynamicModule[{contents={}},EventHandler[Graphics[{PointSize[0.1],Point[Dynamic[contents=Map[If[#[[1,2]]≥0,{#[[1]]-#[[2]],#[[2]]+{0,0.001}},{{#[[1,1]],0},{1,-0.8}#[[2]]}]&,contents];Map[First,contents]]]},PlotRange->{{0,1},{0,1}},ImageSize->80],"MouseDown":>(AppendTo[contents,{MousePosition["Graphics"],{0,0}}])]]

Use dynamic objects as input; click in the different frames to create additional balls:

(%+1)^3//Expand

({{DocumentationFooterIconsRelatedFunction.png, ({{See Also}, {(RefLink[Dynamic, paclet:ref/Dynamic])  ▪  (RefLink[Module, paclet:ref/Module])  ▪  (RefLink[Manipulate, paclet:ref/Manipulate])  ▪  (RefLink[LocalizeVariables, paclet:ref/LocalizeVariables])  ▪  (RefLink[Interpretation, paclet:ref/Interpretation])}})}})

({{DocumentationFooterIconsRelatedTutorial.png, ({{Tutorials}, {▪(RefLinkPlain[Introduction to Dynamic, paclet:tutorial/IntroductionToDynamic])}, {▪(RefLinkPlain[Advanced Dynamic Functionality, paclet:tutorial/AdvancedDynamicFunctionality])}})}})

({{DocumentationFooterIconsRelatedGuide.png, ({{Related Guides}, {▪(RefLinkPlain[Scoping Constructs, paclet:guide/ScopingConstructs])}, {▪(RefLinkPlain[Dynamic Interactivity Language, paclet:guide/DynamicInteractivityLanguage])}, {▪(RefLinkPlain[Low-Level Interface Control, paclet:guide/LowLevelInterfaceControl])}, {▪(RefLinkPlain[Custom Interface Construction, paclet:guide/CustomInterfaceConstruction])}, {▪(RefLinkPlain[Package Development, paclet:guide/PackageDevelopment])}, {▪(RefLinkPlain[Click-Interactive Panels, paclet:guide/ClickInteractivePanels])}, {▪(RefLinkPlain[Control Objects, paclet:guide/ControlObjects])}, {▪(RefLinkPlain[Setting Up User Interactions, paclet:guide/SettingUpUserInteractions])}})}})