Skip to main content
Inspiring
May 31, 2014
Answered

for loop with layer name.

  • May 31, 2014
  • 1 reply
  • 560 views

I am developing a script that checks if the layer color-101 exists in an open document.

If the layer color-101 exists run code block on layer color-101.

If the layer color-101 does not exist run action add color-101 layer.

Return to beginning of loop to check again

I am doing this with a for loop and if statement.

1. Why does the loop not stop when the loop-counting-variable matches the layer name color-101 variable?

2. How can the loop return to the beginning to check again for the presence of layer color-101?


//Decalre varaibles

docRef = app.activeDocument;

var theLayer = "color-101";

//loop through layers

for(var i = 0; i < docRef.layers.length; i++){

       

       //layer name matches loop variable

       if(docRef.layers.name == theLayer){

          

                 //Run code block for layer color-101

                alert ("The layer " + theLayer + " exist. ");

            }

    }

//layer color-101 was not found, run action add color-101 layer

alert ("The " + theLayer + " layer does not exist: Run action add color-101 layer.");

//return to beginning of loop and check again


This topic has been closed for replies.
Correct answer matias.kiviniemi

Your loop does not actually stop from finding the right layer. It just displays the alert popup and then continues. Also the "not found"-part will always trigger. And the comparison has to be 100% equal without case difference or whitespaces or "copy 12"-suffixes.

Try something like

//Declare variables

docRef = app.activeDocument;

var layer_found = false;

 

//loop through layers

for(var i = 0; i < docRef.layers.length; i++){

       var layer = docRef.layers

       if(layer.name.toLowerCase().indexOf("case-101") >= 0){

                alert ("The layer found: " + layer.name);

                layer_found = true

                // do what needs

       }

}

if (!layer_found) {

     alert ("Layer not found!");

     // do what needs

}

1 reply

matias.kiviniemi
matias.kiviniemiCorrect answer
Legend
June 1, 2014

Your loop does not actually stop from finding the right layer. It just displays the alert popup and then continues. Also the "not found"-part will always trigger. And the comparison has to be 100% equal without case difference or whitespaces or "copy 12"-suffixes.

Try something like

//Declare variables

docRef = app.activeDocument;

var layer_found = false;

 

//loop through layers

for(var i = 0; i < docRef.layers.length; i++){

       var layer = docRef.layers

       if(layer.name.toLowerCase().indexOf("case-101") >= 0){

                alert ("The layer found: " + layer.name);

                layer_found = true

                // do what needs

       }

}

if (!layer_found) {

     alert ("Layer not found!");

     // do what needs

}

JJMack
Community Expert
Community Expert
June 1, 2014

The script will only find layers not in a layers group. If the document contains layer groups the routine needs to be reclusive to  process layer groups.

I found this in my collection of junk I have played with. It seems to have a function that processes all art layers.

// A Photoshop Script by JJMack's

// This script processes ArtLayers.

// This script is supplied as is. It is provided as freeware.

// The author accepts no liability for any problems arising from its use.

/*

<javascriptresource>

<about>$$$/JavaScripts/xxxxxxxxxxxxxxxxx/About=JJMack's xxxxxxxxxxxxxxxxx.^r^rCopyright 2009 Mouseprints.^r^rScript utility for action.^rNOTE:Deletes Seleted Area from background and all normal layers.</about>

</javascriptresource>

*/

//<category>JJMack's Script</category>

// enable double-clicking from Mac Finder or Windows Explorer

#target photoshop // this command only works in Photoshop CS2 and higher

// bring application forward for double-click events

app.bringToFront();

// ensure at least one document open

if (!documents.length) {

  alert('There are no documents open.', 'No Document');

}

// if at least one document exists, then proceed

else {

  app.activeDocument.suspendHistory('xxxxxxxxxxxxxxxxx','main()');

}

///////////////////////////////////////////////////////////////////////////////

// main - main function

///////////////////////////////////////////////////////////////////////////////

function main() {

  // declare local variables

  var saveactiveLayer = activeDocument.activeLayer;

  // Set the ruler units to PIXELS

  var orig_ruler_units = app.preferences.rulerUnits;

  app.preferences.rulerUnits = Units.PIXELS;

  try {

  processArtLayers(activeDocument);

  removeAllEmptyLayerSets(activeDocument);

  }

  // display error message if something goes wrong

  catch(e) { alert(e + ': on line ' + e.line, 'Script Error', true); }

  try { activeDocument.activeLayer = saveactiveLayer;}

  catch(e) { } // may have been deleted

  // Reset units to original settings

  app.preferences.rulerUnits = orig_ruler_units;

}

///////////////////////////////////////////////////////////////////////////////

// End - main function

///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////

// Function: processsArtLayers

// Input: document or layer set

// Return: <none>, all layers that were invisible are now gone

///////////////////////////////////////////////////////////////////////////////

function processArtLayers(obj) {

    for( var i = obj.artLayers.length-1; 0 <= i; i--) {

        try {

            processLayer(obj.artLayers);

  }

        catch (e) {

        }

    }

    for( var i = obj.layerSets.length-1; 0 <= i; i--) {

  infoLayer(obj.layerSets);    // Display layerSet informarion

        processArtLayers(obj.layerSets);

    }

}

///////////////////////////////////////////////////////////////////////////////

// Function: removeAllEmptyLayerSets

// Usage: find all empty layer sets and remove them, recursively

// Input: document or layer set

// Return: empty layer sets are now gone

///////////////////////////////////////////////////////////////////////////////

function removeAllEmptyLayerSets(obj) {

    var foundEmpty = true;

    for( var i = obj.layerSets.length-1; 0 <= i; i--) {

        if( removeAllEmptyLayerSets(obj.layerSets)) {

            obj.layerSets.remove();

        } else {

            foundEmpty = false;

        }

    }

    if (obj.artLayers.length > 0) {

  foundEmpty = false;

  }

    return foundEmpty;

}

function processLayer(layer) {

  infoLayer(layer);

}

function infoLayer(layer){

  try{

  alert("layer = " + layer

  + "\rallLocked = " + layer.allLocked

  + "\rblendMode = " + layer.blendMode

  + "\rbounds = " + layer.bounds

  + "\rfillOpacity = " + layer.fillOpacity

// + "\rfilterMaskDensity = " + layer.filterMaskDensity // undefined for groups not valid others ??

// + "\rfilterMaskFather = " + layer.filterMaskFeather // undefined for groups not valid others ??

  + "\rgrouped = " + layer.grouped

  + "\risBackgroundLayer = " + layer.isBackgroundLayer

  + "\rkind = " + layer.kind

  + "\rlayerMaskDensity = " + layer.layerMaskDensity

  + "\rlayerMaskFeather = " + layer.layerMaskFeather

  + "\rlinkedLayers = " + layer.linkedLayers

  + "\rname = " + layer.name

  + "\ropacity = " + layer.opacity

  + "\rparent = " + layer.parent

  + "\rpixelsLocked = " + layer.pixelsLocked

  + "\rpositionLocked = " + layer.positionLocked

// + "\rtextItem = " + layer.textItem // Valid only when kind = LayerKind.TEXT.

  + "\rtransparentPixelsLocked = " + layer.transparentPixelsLocked

  + "\rtypename = " + layer.typename

  + "\rvectorMaskDensity = " + layer.vectorMaskDensity

  + "\rvectorMaskFeather = " + layer.vectorMaskFeather

  + "\rvisible = " + layer.visible

  + "\rxmpMetadata = " + layer.xmpMetadata

  );

  }

  catch(e){

  }

};

/*

allLocked               * boolean read-write. true to completely lock the contents and settings of this layer.

blendMode               * blendmode read-write. the blending mode.

bounds                  * array of unitvalue read-only. an array of coordinates that describes the bounding rectangle of the layer.

fillOpacity             * number [0.0..100] read-write. the interior opacity of the layer, a percentage value.

filterMaskDensity        double read-write. the density of the filter mask (between 0.0 and 250.0)

filterMaskFeather        double read-write. the feather of the filter mask (between 0.0 and 250.0)

grouped                 * boolean read-write. true if this layer is grouped with the layer beneath it.

isBackgroundLayer       * boolean read-write. true if this is the background layer of the document. a document can have only one background layer. if there is no background layer,

                         setting this to true causes this to become the background layer.

kind                    * layerkind read-write. sets the type (such as 'text layer') for an empty layer. valid only when the layer is empty and when isbackgroundlayer.

                         you can use the kind property to make a background layer a normal layer; however, to make a layer a background layer, you must set isbackgroundlayer to true.

layerMaskDensity        * double read-write. the density of the layer mask (between 0.0 and 100.0)

layerMaskFeather        * double read-write. the feather of the layer mask (between 0.0 and 250.0)

linkedlayers            * array of artlayer or layerset read-only. the layers linked to this layer. see artlayer.link.

name                    * string read-write. the name.

opacity                 * number [0.0..100.0]. read-write. the master opacity of the layer, a percentage value.

parent                  * document read-only. the object's container.

pixelsLocked            * boolean read-write. true if the pixels in the layer’s image cannot be edited using the paintbrush tool.

positionLocked          * boolean read-write. true if the pixels in the layer’s image cannot be moved within the layer.

textitem                 textitem read-only. the text item that is associated with the layer. valid only when kind = layerkind.text.

transparentpixelslocked * boolean read-write. true if editing is confined to the opaque portions of the layer.

typename                * string read-only. the class name of the referenced artlayer object.

vectorMaskDensity       * double read-write. the density of the vector mask (between 0.0 and 250.0)

vectorMaskFeather       * double read-write. the feather of the vector mask (between 0.0 and 250.0)

visible                 * boolean read-write. true if the layer is visible.

xmpMetadata             * xmpmetadata read-write. metadata for the layerb

*/

JJMack
ojodegatoAuthor
Inspiring
June 1, 2014

Thanks for providing the script JJ!

I will study the process art layer function to see if can make it work in my context.