javascriptadobe-illustrator

Selecting a set of colors, making a new layer, and then sending to that layer using Illustrator script


I am trying to create an illustrator script that will select a a group of dots that all have the same color and then create a new layer and send it to that layer. The script works when doing one layer, but not with both.

I don't understand what I am doing wrong with my code. When I run the code as is, I get an error of "The operation cannot complete because there is no selection." However, the code still runs, but it moves the yellow dots to the red dots layer and thats it. But, when I comment out either of the selectColor lines with the arguments filled in, it runs correctly with no error and puts the correct dots on the correct new layer.

Any suggestions?

var doc = app.activeDocument;//Gets the active document
var layerName;
var lay = doc.layers;
var myLayer = lay.add();

var yellow = new RGBColor();
yellow.red = 252;
yellow.green = 253;
yellow.blue = 1;

var red = new RGBColor();
red.red = 252;
red.green = 0;
red.blue = 0;




function selectColor(swatch, layerName) {

        var temp = app.documents[0].pathItems.rectangle(10, 10, 150, 150);
        temp.fillColor = swatch;

        // To select object that have CMYK Red swatch applied to fill.
        app.executeMenuCommand('Find Fill Color menu item');

    temp.remove();


    myLayer.name = layerName;
    app.executeMenuCommand('Selection Hat 2');
}

selectColor(yellow, "Yellow Dots");

selectColor(red, "Red Dots");

Solution

  • Steven! As far as I can tell you want this:

    var yellow = new RGBColor();
    yellow.red = 252;
    yellow.green = 253;
    yellow.blue = 1;
    
    var red = new RGBColor();
    red.red = 252;
    red.green = 0;
    red.blue = 0;
    
    function selectColor(swatch, layerName) {
        app.selection = null;
    
        var doc = app.activeDocument;
        var temp = doc.pathItems.rectangle(10, 10, 150, 150);
        temp.fillColor = swatch;
        temp.selected = true;
        app.executeMenuCommand('Find Fill Color menu item');
        temp.remove();
    
        try {
            var myLayer = doc.layers.getByName(layerName);
        } catch (e) {
            var myLayer = doc.layers.add();
            myLayer.name = layerName;
        }
    
        doc.activeLayer = myLayer;
        app.executeMenuCommand('Selection Hat 2'); // send the selection to current layer
    
        app.selection = null;
    }
    
    selectColor(yellow, "Yellow Dots");
    selectColor(red, "Red Dots");