Scrolling to an element in a scrolling frame

I was working on my game and figured out a cool formula for this and just wanted to share it.

How it works
The basic premise is that you take the difference between in the Absolute Position between the element and the top of the scrolling frame and you set the Canvas Position to it.

ScrollingFrame.CanvasPosition = Vector2.new(0, (Element.AbsolutePosition.Y - ScrollingFrame.AbsolutePosition.Y))

In Practice
I put this to work in a loop with 3 elements in it. Each element has a button with an identical name. One bug I encountered was that I needed to get each frames absolute position BEFORE the player started scrolling. I helped to solve this problem by requiring the loop to go through each element BEFORE they can click on one.

The Code
local scroller = script.Parent:WaitForChild("ScrollingFrame")
local loaded = 0
local allButs = script.Parent:WaitForChild("Buttons"):GetChildren()

for i, but in pairs(allButs) do
	if not but:IsA("ImageButton") then continue end
	
	local frame :Frame = scroller:WaitForChild(but.Name)
	local abosPos = frame.AbsolutePosition.Y
	loaded += 1
	
	but.MouseButton1Click:Connect(function()
		
		if loaded < #allButs-1 then return end
		scroller.CanvasPosition = Vector2.new(0, (abosPos - scroller.AbsolutePosition.Y))
		
	end)
end
Video

Thank you for reading my first tutorial, I hope you learned something!

5 Likes

Holy crap, I was just looking for a way to do this for the UI map I’m making. I want the map always to have the player at the center of the map, so I needed a way to get the canvas to always center on the player. You’re a lifesaver, man!

1 Like