Focus

Overview

When you type, your keys go to exactly one place: the search box, the text field, or the button you just moved to. The item that receives the keyboard right now has the focus. Focus is how keyboard users and screen reader users move around an interface, so every interface needs a sensible order for it. In this lesson, you will find out how a form sets the order that the Tab key follows for you, how to change that order when it doesn't match the layout on the screen, how to set the order yourself in a game, and how to make your own items focusable.

Goals

You have the following goals for this lesson:

By the end of this lesson, you can

  • Explain what the focus is and why it matters for keyboard and screen reader users
  • Describe the focus order a form sets for you, and keep labels out of it with SetSkipLabelsInFocus
  • Change a form's focus order, and set a game's focus order, with SetNextFocus and SetPreviousFocus
  • Respond when an item gains or loses the focus
  • Make a custom item focusable, named and described

Warm up

Put your mouse or trackpad aside. Open a website or app you use often and try to do one task, such as searching for something, using only the keyboard. Press Tab to move forward and Shift+Tab to move back. How can you tell where you are? Did the focus ever jump somewhere you did not expect? Was there anything you could click with a mouse but never reach with Tab?

Vocabulary

You will be learning about the following vocabulary words:

Vocabulary
TermDefinition
FocusThe item that receives keyboard input right now. Only one item has the focus at a time.
FocusableAble to receive the focus. Buttons and text fields are focusable; pictures are not, unless you make them focusable.
Focus orderThe order in which Tab moves the focus from item to item. Shift+Tab moves through it backwards.
Default focus orderThe focus order a form works out for you, from the first control on a page to the last.
Focus indicatorWhat shows which item has the focus, such as a highlight or an outline.
Focus listenerAn object that is told whenever an item gains or loses the focus.
Screen readerSoftware that reads the screen aloud, or shows it on a braille display, for people who are blind or have low vision.

New Code to Learn

You will be using the following new pieces of code:

New Code to Learn
Quorum CodeCode ExampleExplanation
SetSkipLabelsInFocus(boolean skipLabelsInFocus)page:SetSkipLabelsInFocus(true)Keeps the labels you add after this line out of the page's focus order.
CalculateDefaultFocusOrdering()page:CalculateDefaultFocusOrdering()Works out the page's focus order now instead of when the form is shown. You can change it afterwards.
SetHasDefaultFocusOrdering(boolean hasDefaultFocusOrdering)page:SetHasDefaultFocusOrdering(true)Tells the page that its focus order is already set. The form then leaves your order alone.
SetNextFocus(Item next)newButton:SetNextFocus(openButton)Sets the item that gets the focus when the user presses Tab.
SetPreviousFocus(Item previous)openButton:SetPreviousFocus(newButton)Sets the item that gets the focus when the user presses Shift+Tab.
Focus()newButton:Focus()Gives the focus to this item. The program must already be running.
SetFocusable(boolean focus)square:SetFocusable(true)Sets whether the item can receive the focus.
GainedFocus(FocusEvent event)action GainedFocus(FocusEvent event)An action that runs when the item gets the focus. You can write your own version of it.
LostFocus(FocusEvent event)action LostFocus(FocusEvent event)An action that runs when the item loses the focus.
AddFocusListener(FocusListener listener)newButton:AddFocusListener(reporter)Tells a listener whenever this item gains or loses the focus.
GetNextFocus()Item next = GetNextFocus()Returns the item that Tab will move to next.

CSTA Standards

This lesson covers the following standards:

For teachers · 2026 CSTA K–12 Computer Science Standards

HS-ALG-IM-09

High School · Algorithms & Design

Design a computing technology using human-centered design principles.

Also in 7 other lessons

MS-ALG-IM-09

Middle School · Algorithms & Design

Evaluate which human-centered design principles are present or missing in an existing computing technology.

Also in 5 other lessons

HS-PRO-TR-19

High School · Programming

Evaluate a computing technology's alignment with design specifications and responsible design values, including its correctness, effectiveness, and user experience.

Also in 7 other lessons

MS-PRO-TR-19

Middle School · Programming

Use systematic strategies to test, refine, and document changes to a computing technology to meet the intended purpose.

Also in 6 other lessons

S1-GMD-PX-05

Specialty I · Game Development

Create a user-friendly interface for a game, considering accessibility, usability, and aesthetics.

Also in 1 other lesson

Every standard, and the lessons that cover it

Explore

What is the focus?

Only one item in a program has the focus at a time. When you press a key, the item with the focus gets it. For example, pressing Space or Enter presses the button that has the focus.

People who do not use a mouse move the focus with the keyboard. Tab moves it forward and Shift+Tab moves it back. A screen reader reads each item as it gets the focus, so for a screen reader user, the focus order is the order of the interface. Clicking an item with the mouse also gives it the focus.

Which items can take the focus?

An item can take the focus only if it is focusable. Some items are focusable from the start, and some are not:

  • Focusable: buttons, check boxes, text fields, text boxes, lists, trees, combo boxes, sliders and most other controls that you interact with.
  • Not focusable at first: pictures, shapes, icons and plain containers. A program can make any of them focusable, as "Making your own focusable item" shows below.
  • Labels on a form page: focusable, so a screen reader user can reach them with Tab. You can turn this off, as explained below.
  • Radio buttons: a group of radio buttons takes the focus as one item. Tab moves into the group, and the arrow keys move between the buttons inside it. If nothing in the group is chosen yet, moving into the group chooses the first button.

You can change this for any item with SetFocusable(true) or SetFocusable(false).

Forms set the focus order for you

In the Forms tutorial, you pressed Tab to move through a page without writing any focus code. That is because a form works out a default focus order when it is shown. It goes through the page from the first control you added to the last, including the controls inside each grouping, and links each one to the next. The last control links back to the first, so Tab goes around in a loop and Shift+Tab goes the other way. Then the form gives the focus to the first focusable item on the page. When a program switches to another page with SetPage, the focus goes to the first item on that page.

The order you add controls is the order they appear on the screen, from top to bottom, so the default focus order usually matches the layout. The easiest way to change the focus order of a form is to change the order you add the controls in.

The following program is a short sign-up page. Each text field has a label beside it, as you saw in the Text Fields tutorial.

use Libraries.Interface.Forms.Form
use Libraries.Interface.Forms.Page
use Libraries.Interface.Controls.TextField
use Libraries.Interface.Controls.Checkbox
use Libraries.Interface.Controls.Button

Form form
Page page = form:GetMainPage()

// Labels added after this line are not in the Tab order.
page:SetSkipLabelsInFocus(true)

page:SetTitle("Join the Chess Club")

page:AddLabel("First name")
TextField firstName = page:AddTextField("First name")
firstName:SetDescription("Type your first name.")

page:AddLabel("Last name")
TextField lastName = page:AddTextField("Last name")
lastName:SetDescription("Type your last name.")

Checkbox reminders = page:AddCheckbox("Send me meeting reminders")
reminders:SetDescription("Check this to get a reminder before each meeting.")

Button join = page:AddButton("Join")
join:SetDescription("Sends your name to the club.")

form:Display()

Run the program and press Tab a few times. The focus goes from the First name field to the Last name field, the check box and the Join button, and then back to the First name field.

Why skip the labels? Each text field already has a name, "First name", and a screen reader reads that name when the field gets the focus. If the label beside it were in the Tab order too, a screen reader user would hear "First name" twice and press Tab twice for every field. Delete the SetSkipLabelsInFocus line and try it.

Two things to know about SetSkipLabelsInFocus:

  • It only affects labels added after it, including the page title. Call it before SetTitle and AddLabel.
  • Keep labels that say something new. A label with instructions, or one that shows a result, should stay in the Tab order, or a screen reader user may never hear it. Skip only labels that repeat a control's name.

Changing a form's focus order

Sometimes the order you add controls is not the order people read them. A grouping with columns is one example. In the Pages tutorial, you put controls in a grouping. SetColumns arranges a grouping's controls in columns, and the controls fill the grid one row at a time, from left to right.

Imagine a made-up table of contents with four chapters in two columns. Like a book's contents page, it reads down the first column, then down the second. To show Chapters 1 and 2 in the first column, the program has to add them in the order 1, 3, 2, 4, and so the default focus order is 1, 3, 2, 4 too. To fix it, the program asks the page to work out its default order right away with CalculateDefaultFocusOrdering, then changes the links between the chapters:

use Libraries.Interface.Forms.Form
use Libraries.Interface.Forms.Page
use Libraries.Interface.Forms.Grouping
use Libraries.Interface.Controls.Button

Form form
Page page = form:GetMainPage()
page:SetTitle("Contents")

Grouping chapters = page:AddGrouping("Chapters")
chapters:SetColumns(2)

// Rows fill from left to right, so the first row holds
// Chapters 1 and 3, and the second row holds Chapters 2 and 4.
Button chapterOne = chapters:AddButton("Chapter 1: Forms")
Button chapterThree = chapters:AddButton("Chapter 3: Behaviors")
Button chapterTwo = chapters:AddButton("Chapter 2: Pages")
Button chapterFour = chapters:AddButton("Chapter 4: Focus")

Button close = page:AddButton("Close")
close:SetDescription("Closes the table of contents.")

// Work out the default order now, so it can be changed.
page:CalculateDefaultFocusOrdering()

// Read down each column: 1, 2, 3, 4, then Close.
chapterOne:SetNextFocus(chapterTwo)
chapterTwo:SetPreviousFocus(chapterOne)
chapterTwo:SetNextFocus(chapterThree)
chapterThree:SetPreviousFocus(chapterTwo)
chapterThree:SetNextFocus(chapterFour)
chapterFour:SetPreviousFocus(chapterThree)
chapterFour:SetNextFocus(close)
close:SetPreviousFocus(chapterFour)

form:Display()

CalculateDefaultFocusOrdering also marks the page's order as set, so the form does not work it out again, and replace your changes, when it is shown. The program changes only the links that were wrong. The links from the page title to Chapter 1 and from Close back to the title come from the default order.

If you want to set every link yourself, call page:SetHasDefaultFocusOrdering(true) instead. The form then sets no links at all, and Tab reaches only the items you link.

One more rule: Focus() gives the focus to an item, but only once the program is running. In a form, call it from a behavior, never before Display.

Focus inside a control

Some controls keep the focus on themselves while you move around inside them. When a combo box's list is open, for example, the arrow keys move through the choices, but the focus stays in the combo box's text field, so you can keep typing. The control tells screen readers which choice is highlighted, so they read the choice the arrow keys just moved to. That highlighted part is called the active descendant, and GetActiveDescendant returns it. You don't need to do anything to make this work in Quorum's controls.

Setting the focus order in a game

A program that uses the Game class doesn't work out a focus order. Until you set one, pressing Tab does nothing, because no item knows which item comes next. And until some item has the focus, Tab has nowhere to start from.

Each item stores two links:

  • SetNextFocus sets where Tab goes from this item.
  • SetPreviousFocus sets where Shift+Tab goes from this item.

The following program has three buttons. It links them in a loop, so that Tab goes from New to Open to Save and back to New. It then gives the focus to New with Focus(), so the keyboard works as soon as the program starts.

use Libraries.Game.Game
use Libraries.Interface.Controls.Button
use Libraries.Interface.Layouts.FlowLayout

class Main is Game
    action Main
        StartGame()
    end

    action CreateGame
        FlowLayout layout
        SetLayout(layout)

        Button newButton
        newButton:SetName("New")
        newButton:SetDescription("Starts a new drawing.")

        Button openButton
        openButton:SetName("Open")
        openButton:SetDescription("Opens a saved drawing.")

        Button saveButton
        saveButton:SetName("Save")
        saveButton:SetDescription("Saves this drawing.")

        // Tab order: New, Open, Save, then back to New.
        newButton:SetNextFocus(openButton)
        openButton:SetNextFocus(saveButton)
        saveButton:SetNextFocus(newButton)

        // Shift+Tab order: the same loop, backwards.
        newButton:SetPreviousFocus(saveButton)
        openButton:SetPreviousFocus(newButton)
        saveButton:SetPreviousFocus(openButton)

        FocusReporter reporter
        newButton:AddFocusListener(reporter)
        openButton:AddFocusListener(reporter)
        saveButton:AddFocusListener(reporter)

        Add(newButton)
        Add(openButton)
        Add(saveButton)

        newButton:Focus()
    end

    action Update(number seconds)
    end
end

The FocusReporter is a focus listener: an object that is told whenever an item it listens to gains or loses the focus. Here it writes the name of the item that just got the focus to the output. Put it in its own file, FocusReporter.quorum:

use Libraries.Interface.Events.FocusListener
use Libraries.Interface.Events.FocusEvent
use Libraries.Interface.Item

class FocusReporter is FocusListener
    action GainedFocus(FocusEvent event)
        Item item = event:GetNewFocus()
        if item not= undefined
            output "The focus moved to " + item:GetName()
        end
    end
end

Run the program and press Tab a few times, then Shift+Tab. Each time, the output shows where the focus went, and the button with the focus is highlighted. A screen reader reads the button's name, its description and that it is a button.

Making your own focusable item

Shapes and pictures are not focusable, but you can make them focusable and decide what happens when they gain or lose the focus. Every item has two actions for this, GainedFocus and LostFocus, which do nothing by default. If you make your own class that inherits from an item class, you can write your own versions of them.

The following class is a Drawable, a shape you can draw, that turns green and grows a little while it has the focus, and turns red and goes back to its size when it loses the focus. Changing the size as well as the color helps people who cannot easily tell red from green. When it is made, it also makes itself focusable and gives itself an accessibility code, so screen readers know it is there. Put it in a file named FocusDrawable.quorum:

use Libraries.Game.Graphics.Drawable
use Libraries.Game.Graphics.Color
use Libraries.Interface.Events.FocusEvent

class FocusDrawable is Drawable
    on create
        // Shapes are not focusable, or known to screen readers, by default.
        SetFocusable(true)
        SetAccessibilityCode(parent:Item:ITEM)
    end

    action GainedFocus(FocusEvent event)
        Color color
        SetColor(color:Green())
        SetScaleFromCenter(1.25)
        output GetName() + " has the focus."
    end

    action LostFocus(FocusEvent event)
        Color color
        SetColor(color:Red())
        SetScaleFromCenter(1.0)
    end
end

The main program makes three shapes, gives each one a name and a description, and links them in a loop from left to right:

use Libraries.Game.Game
use Libraries.Game.Graphics.Color

class Main is Game
    action Main
        StartGame()
    end

    action CreateGame
        Color color
        FocusDrawable square
        FocusDrawable circle
        FocusDrawable triangle

        square:LoadFilledRectangle(80, 80, color:Red())
        circle:LoadFilledCircle(40, color:Red())
        triangle:LoadFilledTriangle(0, 0, 40, 80, 80, 0, color:Red())

        square:SetPosition(150, 250)
        circle:SetPosition(350, 250)
        triangle:SetPosition(550, 250)

        square:SetName("Square")
        square:SetDescription("A red square. It turns green when it has the focus.")
        circle:SetName("Circle")
        circle:SetDescription("A red circle. It turns green when it has the focus.")
        triangle:SetName("Triangle")
        triangle:SetDescription("A red triangle. It turns green when it has the focus.")

        square:SetNextFocus(circle)
        circle:SetNextFocus(triangle)
        triangle:SetNextFocus(square)
        square:SetPreviousFocus(triangle)
        circle:SetPreviousFocus(square)
        triangle:SetPreviousFocus(circle)

        Add(square)
        Add(circle)
        Add(triangle)

        square:Focus()
    end

    action Update(number seconds)
    end
end
Blocks

Two lines in FocusDrawable are easy to forget:

  • SetFocusable(true). Without it, Focus() and Tab skip the shape.
  • SetAccessibilityCode(parent:Item:ITEM). A shape is hidden from screen readers by default, because most shapes are decoration. Giving it the ITEM code tells the screen reader that it is something the user can move to, so the screen reader can read its name and description. The Accessibility tutorial describes the other codes. ITEM is a constant of the Item class, so the class reaches it through parent:Item:.

Looking ahead with GetNextFocus

An item can also tell you where the focus will go next. GetNextFocus returns the item that Tab moves to, and GetPreviousFocus returns the item that Shift+Tab moves to. Either one is undefined if no link was set.

For example, you can change GainedFocus in FocusDrawable to write where Tab and Shift+Tab will go. Add use Libraries.Interface.Item to the top of the file, and replace the output line with:

Item next = GetNextFocus()
Item previous = GetPreviousFocus()
if next not= undefined and previous not= undefined
    output GetName() + ". Tab for " + next:GetName() + ", Shift+Tab for " + previous:GetName() + "."
end

A good focus order

A focus order is a design choice, and a careless one makes a program hard to use. Whether a form sets it or you do, check that:

  • It follows the reading order. Usually left to right, then top to bottom, in the same order the items appear on the screen. Groupings with columns may need help, as shown above.
  • It reaches everything. Every item a person can click should also be reachable with Tab.
  • It does not trap the user. Shift+Tab should always lead back. A loop, like the ones in this lesson, is one simple way.
  • It starts somewhere useful. A form starts at the first item on the page. In a game, call Focus() on the first item, so the keyboard works right away.
  • It has no extra stops. Labels that repeat a control's name can be skipped with SetSkipLabelsInFocus.
  • Every focusable item has a name. Otherwise a screen reader can only say "button" or nothing at all.
  • The focus is visible. Controls draw a focus outline for you. If you make your own focusable item, make it change in a way that does not rely on color alone.

Engage

The goal of this activity is to hold a crazy focus contest. Build a form page with at least six controls, such as some text fields with labels, a check box and a grouping of buttons. Then use what you learned on this page, such as SetNextFocus and SetPreviousFocus, to give it the craziest focus order you can. There is one rule: pressing Tab over and over must still reach every control on the page, and Shift+Tab must still go back the way it came. Before anyone tries it, plan your order on paper or with physical manipulatives.

Then hold the contest, with a partner or as a class. Swap programs and try each one with the keyboard, and with a screen reader if one is available. Check that every entry follows the rule: if a control can't be reached, the entry is out. Then vote for the winner: the order that is the most surprising but still reaches everything.

Last, fix the winner. Together, suggest changes that would make its order less crazy: which control should come first, which controls belong next to each other, and where Tab should go after the last control. Make the changes, and explain how each one makes the page easier to use.

Wrap up

Before this lesson, had you ever noticed the focus in the programs you use? Think of a program where the Tab key did something surprising. Now that you know how focus order is set, what do you think its programmers forgot? When would you trust a form's default order, and when would you check it by hand?