So I'm typing in a text frame and I decide to run a script.
I'd like that script to refer to the text frame that my cursor is already in.
In Javascript, how do I refer to that particular textFrame?
So I'm typing in a text frame and I decide to run a script.
I'd like that script to refer to the text frame that my cursor is already in.
In Javascript, how do I refer to that particular textFrame?
Consider the following gist:
var selectedItem = app.activeDocument.selection[0];
if (selectedItem instanceof InsertionPoint &&
selectedItem.parentTextFrames[0] instanceof TextFrame) {
var textFrame = selectedItem.parentTextFrames[0];
// This just demonstrates that the variable `textFrame` does
// hold a reference to the actual text frame - let's delete it !
textFrame.remove();
} else {
alert("The cursor has not been placed in a text frame");
}
Explanation:
Firstly we obtain a reference to whatever is selected in the document via the line reading:
var selectedItem = app.activeDocument.selection[0];
We then infer whether the type of selection equates to a "cursor in a Text Frame" by:
instanceof InsertionPoint
.parentTextFrames
is a TextFrame
.if (selectedItem instanceof InsertionPoint &&
selectedItem.parentTextFrames[0] instanceof TextFrame) {
// ... If we get here, then the "cursor is in a Text Frame".
}
If the conditional checks that infer whether the "cursor is in a Text Frame" are true
then we proceed to assign the Text Frame's reference to a variable named textFrame
. i.e.
var textFrame = selectedItem.parentTextFrames[0];
Just to demonstrate that the variable textFrame
does hold a reference to the actual text frame we delete it !
textFrame.remove(); // Do stuff with the text frame !
If the conditional checks that infer whether the "cursor is in a Text Frame" are false
then we alert the user that "The cursor has not been placed in a text frame".
Selected text characters in a Text Frame
Maybe the user has selected text characters in a text Frame, instead of just placing the cursor in a text frame. If you wanted to get the Text Frame reference in this scenario too - then change your conditional check in the gist above to something like this:
if ((selectedItem instanceof InsertionPoint || selectedItem instanceof Text)
&& selectedItem.parentTextFrames[0] instanceof TextFrame) {
// ...
}