Skip to main content
studiovanzwet
Participating Frequently
August 31, 2022
Answered

Get array of colors in swatch Group

  • August 31, 2022
  • 1 reply
  • 835 views

Hi All,

I'm trying to get an array of swatchnames in a swatch group I created in a Indesign Template, so I can random pick a color of that array.

 

var template = app.open (File ('~/Desktop/test.indt'));
// Do stuff

var palette = app.swatchGroups.getByName("mypallete").swatches;
alert(palette[0].name);

 

How can I get the swatchGroup?

 

Cheers, Dennis

This topic has been closed for replies.
Correct answer m1b

Hi, 

 

Can I store the colorGroupSwatches in 'myColorArray'? So I can pick a random color, delete it from the array (with splice), and repeat untill there are no more items in the array (array.length)

 

//example array
myColorArray = [
[100,0,0,0],[0,100,0,0],[0,0,100,0],[0,0,0,100]
];

for ( var i=0 ;  i<myColorArray.length; i++ ) {
            var randomFromArray = Math.floor(Math.random()*myColorArray.length); 
            var myRandomColor = myColorArray[randomFromArray];

            //do something, for example fill a square with that color

            // remove the color we selected so it can't be selected next time.
            myColorArray.splice(randomFromArray,1); 
 }

 


Hi @studiovanzwet, if you want the colors in an Array, you can put them in one:

var myColors = [];

for (var i = 0;i < doc.colorGroups[1].colorGroupSwatches.length; i++)
    myColors.push(doc.colorGroups[1].colorGroupSwatches[i].swatchItemRef);

// now we have the colors in an Array
// so we can use any Array method

var firstColor = myColors.shift();

- Mark

1 reply

m1b
Community Expert
Community Expert
August 31, 2022

Hi @studiovanzwet, they are best accessed through a Document, and are called "colorGroups", with swatches in "colorGroupSwatches" property, so

 

 

var palette = doc.colorGroups.itemByName("mypallete").colorGroupSwatches;

 

 

See documentation.

 - Mark

 

Edit: oops, itemByName, not getByName.

studiovanzwet
Participating Frequently
August 31, 2022

Hi Mark,

 

Thank you for your quick reply, that link is very usefull. Is it getByName or itemByName. Would this var be a array?

 

Cheers,

Dennis

m1b
Community Expert
Community Expert
August 31, 2022

No it isn't an Array, it is a ColorGroupSwatches object. It does work like an Array in some ways though, for example you can access its members by index.

// get ColorGroupSwatches of 3rd colorGroup of doc
var myColorGroupSwatches = doc.colorGroups[2].colorGroupSwatches;

// make an index to random element of myColorGroupSwatches
var index = Math.floor(Math.random() * myColorGroupSwatches.length);

// get the Color object at that index in myColorGroupSwatches
var myRandomColor = myColorGroupSwatches[index].swatchItemRef;

$.writeln('myRandomColor = ' + myRandomColor.name);

 - Mark