I am making an Illustrator CS6 Javascript that does the following:
My script works except, it doesn't loop through the files in the source folder correctly. Instead, it runs fine on the first source file. But then it endlessly just pastes the second source file in the destination document (I.e. it doesn't move onto any of the other source file). It just endlessly pastes and so I have to force quit!
How can I get it to loop through the folders properly and then move onto the next file.
Here is my code:
// JavaScript Document
//Set up vairaibles
var destDoc, sourceDoc, sourceFolder, newLayer;
// Select the source folder.
sourceFolder = Folder.selectDialog('Select the folder with Illustrator files that you want to mere into one', '~');
destDoc = app.documents.add();
// If a valid folder is selected
if (sourceFolder != null) {
files = new Array();
// Get all files matching the pattern
files = sourceFolder.getFiles();
if (files.length > 0) {
// Get the destination to save the files
for (i = 0; i < files.length; i++) {
sourceDoc = app.open(files[i]); // returns the document object
var myLayers = sourceDoc.layers; // Select All layers in Active Document
//Go through all layers of source document and copy artwork
for (i = 0; i < myLayers.length; i++) {
myLayers[i].hasSelectedArtwork = true;
};
with(sourceDoc) {
var count = pageItems.length;
for (var i = 0; i < count; i++) {
pageItems[i].selected = true;
}
redraw();
copy();
for (var i = 0; i < count; i++) {
pageItems[i].selected = false;
}
}
//Create a new title variable that has the title of the source document
var title = sourceDoc.name;
var title = title.substring(0, title.length - 4); //(remove extension from name)
//Close the Source Document
sourceDoc.close(SaveOptions.DONOTSAVECHANGES);
//Open the Destination Document and create a new layer in it that is named after the title variation
newLayer = destDoc.layers.add();
newLayer.name = title;
//Paste into this new layer
newLayer = app.paste();
}
}
else {
alert('No matching files found');
}
}
Ps. I wasn't sure if I should post this in Code Review or Graphic Design, but I think Stack overflow is the best place to post this as it is a general question about javascript looping, so I hope this is the right place.
It appears that you are using "i" for the variable in each of your loops, giving it a range of unexpected values in other loops that also use that same variable. I would try using a separate variable for each loop. E.g. for j=0, for k=0, for l=0, etc.