Problem: We want to add a pop-up box to a TextArea control as a user is types a specific word or set of words into a TextArea control. The pop-up box should needs to be at the position of the cursor, but we don’t know the x & y position of the cursor.
Solution: With a little coercion and the TextLineMetrics class, we can approximate the x & y position of the cursor.
Example using a TextArea control with the id of myTextArea:
var textHeight:Number = myTextArea.textHeight;
var lineHeight:Number = myTextArea.getLineMetrics( 0 ).height;
var numLines:Number = Math.ceil( textHeight/lineHeight );
var currentLineMet:TextLineMetrics = myTextArea.getLineMetrics( numLines-1 );
var xPos:Number = currentLineMet.width + myTextArea.x;
var yPos:Number = textHeight + predict_ti.y – ( lineHeight * myTextArea.verticalScrollPosition );
The TextLineMetrics class contains information about the text position and measurements of a line of text within a text field. All of the measurements are in pixels, so we are just aproximating the x & y position.
The problem with the above example is that it only works for the last character that you type into the TextArea. If we want to get the actual cursor position we’ll need to create a custom component using the a TextField.
Below is a link to a simple component that figures out an approximate x & y based on the index of the character 1 less than the current position of the carat within the TextField.