Move Layer To The Top

Hello!
I have been using both approach a lot in my scripts, and I feel like sharing one thing or two about moving a layer to the top.

Option #1:

var currentDocument = app.activeDocument;
var layers = currentDocument.activeLayers;
var SelectedLayer = layers[0];
SelectedLayer.moveAbove(currentDocument.layerTree[0]);

Option #2:

batchPlay(
[
   {
      "_obj": "move",
      "_target": [
         {
            "_ref": "layer",
            "_enum": "ordinal",
            "_value": "targetEnum"
         }
      ],
      "to": {
         "_ref": "layer",
         "_enum": "ordinal",
         "_value": "front"
      },
      "_isCommand": true,
      "_options": {
         "dialogOptions": "dontDisplay"
      }
   }
],{ });

In fact, both options seems to be equivalent at first, but they yeild different results, especially if you have nested Groups & Layers in the PS layers stack.
Let’s have a closer look.
.
.

Case 1
PS stack with a bunch of layers, one group and a layer inside:

Let’s say we want to move the Yellow layer “Layer 3” to the top.

Using Option #1 or Option #2 will give the same result:


Indeed, moving the yellow “Layer 3” to the top is done in the same fashion with either Option #1 or Option #2.
That’s good :slight_smile:

.
.

Now, let’s examine the case where Option #1 and Option #2 begins to show different results.

Case 2
Consider this layer stack with nested groups:

Let’s say we want to move the Red layer “Layer 3” to the top.

This is the result when using Option #1

.

And this is the result when using Option #2

A-ha! :sweat_smile:
As you can see, Option #1 and Option #2 are not equivalent anymore.
Beware of nested Groups & Layers structure.
.
.

Conculsion:

  • Option #2 moves “Layer 3” to the top, yes, but to the top of the group it was contained in. Note: If you’d wat to move it at the very top of the PS stack, you’d have to call batchPlay Option#2 twice (in this particular case because of nested levels).

  • On the other hand, Option #1 moves “Layer 3” to the top of the layer stack itself.
    If you want to be extra-sure that “Layer 3” will be move to the top regardless of the PS stack structure, then Option #1 is probably your best friend.

Personally, I consider Option #1 to be the safest. It does what it should be doing: move the layer to the (very) top, no matter how the PS stack looks like.

Finally, it depends on your particular need and expectations.

Hope this helps :slight_smile: