Applying random weight values to individual characters in a variable font
Hello!
I am trying to apply different random weight values to each character in a text frame that uses a variable font in InDesign. I've attempted to write a script to achieve this, but I'm having trouble getting it to work as intended. Here's the code I've written:
if (app.documents.length > 0 && app.selection.length > 0) {
var selectedItem = app.selection[0];
if (selectedItem.constructor.name === 'TextFrame') {
randomizeFontWeight(selectedItem);
} else {
alert('Please select a text frame.');
}
} else {
alert('Please open a document and select a text frame.');
}
function randomizeFontWeight(textFrame) {
var appliedFont = textFrame.parentStory.appliedFont;
var fontFamily = appliedFont.fontFamily;
if (fontFamily === 'Acumin Variable Concept') { // Replace 'Acumin Variable Concept' with the name of the variable font you want to apply.
var fontWeightRange = [100, 800];
var fontWeightList = ['Thin', 'ExtraLight', 'Light', 'Regular', 'Medium', 'SemiBold', 'Bold', 'ExtraBold', 'Black'];
for (var i = 0; i < textFrame.characters.length; i++) {
var randomWeight = Math.floor(Math.random() * (fontWeightRange[1] - fontWeightRange[0] + 1)) + fontWeightRange[0];
var randomIndex = Math.floor(Math.random() * fontWeightList.length);
var randomFontStyle = fontWeightList[randomIndex];
var myTextRange = textFrame.characters[i].textStyleRanges[0];
myTextRange.appliedFont = appliedFont;
var myTextRange = textFrame.characters[i].textStyleRanges[0]; myTextRange.applyCharacterStyle(myCharacterStyle);
var myCharacterStyle = textFrame.parentStory.characterStyles.add();
myCharacterStyle.name = "RandomFontStyle";
myCharacterStyle.fontStyle = randomFontStyle;
myTextRange.applyCharacterStyle(myCharacterStyle);
}
} else {
alert('Please select a text frame with a variable font applied.');
}
}
My goal is for each character in the selected text frame with a variable font applied to have its own unique random weight value. However, my code doesn't seem to be working properly. Can anyone suggest a solution or help me improve this script to achieve my desired result?
Thank you!
*I've chosen the variable font "Acumin" and included it in the code. However, it would be better if the script could apply to any variable font, rather than specifying a particular variable typeface in the code.
