Skip to main content
Known Participant
April 18, 2020
Question

Sorting the layers and using a loop

  • April 18, 2020
  • 4 replies
  • 1095 views

Hello,

I have such part of code. It is sorting me the layers in proper order.

My question is how to use a loop of existence of every layer for that ? "Check if such given layer exists, use the code. When it doesn't exist, go to the next layer" ?

 

"

var aLay = app.activeDocument.layers.getByName("tertiary");
aLay.zOrder( ZOrderMethod.BRINGTOFRONT);

var aLay = app.activeDocument.layers.getByName("secondary");
aLay.zOrder( ZOrderMethod.BRINGTOFRONT);

var aLay = app.activeDocument.layers.getByName("primary");
aLay.zOrder( ZOrderMethod.BRINGTOFRONT);

 

"

This topic has been closed for replies.

4 replies

BeffAuthor
Known Participant
April 20, 2020

Thank you. They are working great.

 

I still have problems with these kind of loop.

CarlosCanto
Community Expert
Community Expert
April 20, 2020
For me it would be ideal if script checks if such layer exists, then bring it to front. When it doesn't exist, do nothing.

it would be ideal for me as well, but there isn't a command to check for layer existance

 

No, no, I needn't catch errors.

checking for errors is a way of telling if a layer exists

 

 

CarlosCanto
Community Expert
Community Expert
April 19, 2020

you can use a try/catch to trap errors

 

var idoc = app.activeDocument;
try {
var ilayer = idoc.layers.getByName('Layer 2');
// DO SOMETHING
alert(ilayer.name);
}
catch(e) {
// DO SOMETHING ELSE
alert(e);
}
BeffAuthor
Known Participant
April 19, 2020

No, no, I needn't catch errors.

 

For me it would be ideal if script checks if such layer exists, then bring it to front. When it doesn't exist, do nothing.

Then next layer the same, and next and next...

 

These are only three example layers.

femkeblanco
Legend
April 19, 2020

Loop thru layers and check if a named-layer exists; if so, bring to front; if not, check if a next named-layers exists:

 

 

for (var i = 0; i < activeDocument.layers.length; i++) {
 if (activeDocument.layers[i].name == "tertiary") {
   activeDocument.layers["tertiary"].zOrder(ZOrderMethod.BRINGTOFRONT);
 }
 if (activeDocument.layers[i].name == "secondary") {
   activeDocument.layers["secondary"].zOrder(ZOrderMethod.BRINGTOFRONT);
 }
 if (activeDocument.layers[i].name == "primary") {
   activeDocument.layers["primary"].zOrder(ZOrderMethod.BRINGTOFRONT);
 }
}

 

 

femkeblanco
Legend
April 19, 2020

What do you mean by "proper order"?  Do you want the first-created to be topmost?  Or do you want them ordered by name ("primary" to be topmost)? 

 

 

BeffAuthor
Known Participant
April 19, 2020

No, no, it is working nice now. It is sorting me the layers from the top in this order: primary, secondary, tertiary.

But when for example there is no layer "secondary", then the script crashes in that moment.