Sub topic 18
Automating Layer Creation and Grouping with a Script
Prerequisites and the scripting model
This chapter assumes that you can open a Photoshop document, use the Layers panel, and distinguish pixel layers from groups. It also assumes basic JavaScript syntax. Photoshop scripts can automate repeated layer tasks through its scripting object model. The object model is a set of objects and properties that represent the active document, layers, groups, and other Photoshop features.
A Photoshop script usually starts with app.activeDocument. This refers to the document currently open and active. The script can then create objects, set their properties, and move them in the layer stack.
Create a layer and group it
Save the following text as a file ending in .jsx. In Photoshop, run it with File > Scripts > Browse, then select the file.
// ExtendScript (.jsx): create a named layer and a group, then put the layer inside the group
var doc = app.activeDocument;
var layer = doc.artLayers.add();
layer.name = "Highlights";
var group = doc.layerSets.add();
group.name = "Lighting";
layer.move(group, ElementPlacement.INSIDE);doc.artLayers.add() creates a pixel layer. The script stores that layer in the layer variable and names it Highlights.
doc.layerSets.add() creates a layer group. A layer group is a container that holds layers and other groups. The script names the group Lighting.
The move() method changes the layer's position. ElementPlacement.INSIDE places the pixel layer inside the group. The group and layer then appear in the Layers panel as a parent-child relationship.
The script creates both objects at the top level before moving the layer. This makes the sequence easy to read and gives you separate references to both objects.
Extend the pattern
You can repeat the creation steps to build a predictable file structure. For example, create groups named Background, Lighting, and Color, then place related pixel layers inside each group. Consistent names make later automation and manual editing easier.
Nested groups use the same layerSets.add() method. Create a subgroup, then move it inside an existing group:
var effects = group.layerSets.add();
effects.name = "Effects";Here, group is the Lighting group created earlier. The new Effects group becomes nested inside it.
Common errors
- Running the script with no open document causes
app.activeDocumentto fail. - Misspelling
ElementPlacement.INSIDEprevents the move operation. - Creating a group does not automatically place later layers inside it. Move each layer explicitly.
- A script that assumes a fixed layer name can fail after a user renames that layer.
Exercise
Which line creates the parent-child relationship between the Highlights layer and the Lighting group?
Show answer
layer.move(group, ElementPlacement.INSIDE); moves the layer inside the group.