GettingStarted
Illustrator JavaScript 2
Example 1: Acting on Selected Objects
When the user makes a selection in a displayed document, the selected objects are stored in the
document’s
selection
property. To access all selected objects in the active document:
var selectedObjects = app.activeDocument.selection;
Depending on what is selected, the property value can be either an array of art objects or a text string. To
correctly handle the selection, you must first test to see if you have artwork or text. To get or manipulate
the properties of the selected art items, you must retrieve the individual items in the array. For example,
the topmost object is at the zero index in the array:
var topObject = app.activeDocument.selection[0]; // for topmost object
The following example gets all the selected objects and then displays the type names for theselected
items or returns an appropriate message.
1. Open a new blank document in your text editor. For example, in Textpad, choose
File>New
.
2. Save the document as
Example1.js
. For example, in Textpad, choose
File>Save
.
3. Write the initial statements declaring the variables.
//Declare and initialize variables
var msgType = "";
4. This script has to run on objects in a document, so make sure a document is open.
// check if a document is open in Illustrator.
if( app.documents.length > 0)
{
5. If the document is open, get the selected objects.
mySelection = app.activeDocument.selection;
6. Check if there were any objects selected.
if (mySelection.length > 0)
{
7. If there are selected object, use a loop to get their type names from the
typename
property, and assign
an appropriate message to the
msgType
variable.
msgType = "Selection items: \n";
for (var i=0; i<mySelection.length; i++)
{
m= "\nItem " + i + " typename is: " + mySelection[i].typename;
}
}
If no objects were selected, assign a message to that effect.
else
{
msgType = "Nothing is selected.";
}
}