Automatic scroll on tab focus

Tagged:  

A common requirement in a Flex application is to make the page automatically scroll to show the field that you tabbed into.

Here's one way to do this:

In your main application, add an event listener for focusIn, and handle it like this:

private function globalFocusInHandler(event:FocusEvent):void {
	var pt:Point = new Point();
	if (verticalScrollPolicy == ScrollPolicy.ON) {
		pt = DisplayObject(event.target).localToGlobal(pt);
		var targetHeight:Number = DisplayObject(event.target).height;
		if (targetHeight > 100) return;
		var yVal:Number = pt.y + targetHeight;
		var minY:Number = yVal - (height -  verticalScrollPosition) + 30;
		if (minY > verticalScrollPosition) {
			verticalScrollPosition = minY;
		}
	}
}

What this does, is no matter how you focus into an item (and it doesn't matter what kind of item it is), the application will scroll to show that field.

This code is intended for auto-scrolling the vertical scrollbar for the main application.