Search code examples
colorsadobeadobe-illustrator

adobe illustrator script- check if swatch color is on list


I'm trying to make a script that will go through the swatches list and will search for a swatch named "Line". if it will not be found I want to add it but if it already been found I want the script to be ignored.

this is what I did so far, the problem is that if it finds a swatch named "Line" it will create a new pink color for some reason.

var doc = app.activeDocument;

for (i = 0; i < doc.swatches.length; i++)
{
   if (doc.swatches[i].name != "Line")
   {
       var newSpot = doc.spots.add();

        var newColor = new CMYKColor();
        newColor.cyan = 100;
        newColor.magenta = 100;
        newColor.yellow = 100;
        newColor.black = 100;

        newSpot.name = "Line";
        newSpot.colorType = ColorModel.SPOT;
        newSpot.color = newColor;
   }
}

Solution

  • You can try to pick the color by its name first and create a new color only if there is the error:

    var doc = app.activeDocument;
    
    try { var color = doc.swatches.getByName('Line') }
    
    catch(e) {
    
        var newColor = new CMYKColor();
            newColor.cyan    = 100;
            newColor.magenta = 100;
            newColor.yellow  = 100;
            newColor.black   = 100;
    
        var newSpot = doc.spots.add();
            newSpot.name      = 'Line';
            newSpot.colorType = ColorModel.SPOT;
            newSpot.color     = newColor;
    }