How do I see where the cursor is in a textbox

I want to make a frame that follows the cursor in a text box. So pretty much getting the UDim2 of the position of the cursor.

You can use InputChanged

local gui:GuiObject = 
game:GetService("UserInputService").InputChanged:Connect(function(Input)
	if Input.UserInputType == Enum.UserInputType.MouseMovement then
		gui.Position = UDim2.fromOffset(Input.Position.X, Input.Position.Y)
	end
end)

UserInputType will verify that the input is the mouse moving and if necessary do other calculations in case the GuiObject is the child of another GuiObject.

You can do

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

mouse.Move:Connect(function()
  local pos = Udim2.fromOffset(mouse.X,mouse.Y)
  -- move frame
end)

I guess there’s kind of 2 cursors. The one I mean is where the blinking line is in the textbox where you’re about to type.

Oh, maybe the CursorPosition property is what you are looking for.

the frame will follow the cursor? when the cursor is inside the textbox?

I want it to return to a position that I can use. CursorPosition just shows the bytes.

The frame will follow the cursor in the text box. What I’m making is an autofill thing like what shows in a script
image

oh just put a local script and a frame inside the textbox
the code:

script.Parent.Changed:Connect(function()
	script.Parent.Frame.Position = UDim2.new(0, script.Parent.TextBounds.X, 0, script.Parent.TextBounds.Y)
end)
1 Like

So you just have to use TextBounds, TextXAlignment and some math

local textBox = script.Parent
textBox.Changed:Connect(function()
	if textBox.TextXAlignment == Enum.TextXAlignment.Center then
		local Scale = (textBox.TextBounds.X/textBox.AbsoluteSize.X)/2
		textBox.Frame.Position = UDim2.fromScale(0.5 + Scale, 0)
		
	elseif textBox.TextXAlignment == Enum.TextXAlignment.Left then
		local Scale = (textBox.TextBounds.X/textBox.AbsoluteSize.X)
		textBox.Frame.Position = UDim2.fromScale(Scale, 0)
		
	elseif textBox.TextXAlignment == Enum.TextXAlignment.Right then
		local Scale = (textBox.TextBounds.X/textBox.AbsoluteSize.X)
		textBox.Frame.Position = UDim2.fromScale(-Scale, 0)
		
	end
end)

Example:


It could be made a little more compact, but this is the simplest, and if Y also varies, it is the same formula but on the Y axis and with TextYAlignment.

3 Likes

Huh, that was surprisingly simple. Thanks.

1 Like