Files
cypress/docs/source/api/commands/focus.md
T

2.6 KiB

title, comments
title comments
focus false

Focus on a DOM element.

Syntax

.focus()
.focus(options)

Usage

{% fa fa-check-circle green %} Correct Usage

cy.get('input').first().focus() // Focus on the first input

{% fa fa-exclamation-triangle red %} Incorrect Usage

cy.focus('#search')  // Errors, cannot be chained off 'cy'
cy.window().focus()  // Errors, 'window' does not yield DOM element

Arguments

{% fa fa-angle-right %} options (Object)

Pass in an options object to change the default behavior of .focus().

Option Default Description
log true {% usage_options log %}
timeout {% url defaultCommandTimeout configuration#Timeouts %} {% usage_options timeout .focus %}

Yields {% helper_icon yields %}

{% yields same_subject .focus %}

Examples

Focus

Focus on an input

cy.get('[type="input"]').focus()

Focus, type, and blur a textarea

// yields the <textarea> for further chaining
cy.get('textarea').focus().type('Nice Product!').blur()

Notes

Cypress blurs other focused elements first

If there is currently a different DOM element with focus, Cypress issues a blur event to that element before running the .focus() command.

Can only be called on a valid focusable element.

Ensure the element you are trying to call .focus() on is a {% url 'focusable element' https://www.w3.org/TR/html5/editing.html#focusable%}. Most commonly, you'll want to ensure that the element is not disabled, although there are {% url 'other factors' https://www.w3.org/TR/html5/editing.html#focusable%}.

Can time out because your browser did not receive any focus events.

If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is run.

Rules

Requirements {% helper_icon requirements %}

{% requirements focusability .focus %}

Assertions {% helper_icon assertions %}

{% assertions wait .focus %}

Timeouts {% helper_icon timeout %}

{% timeouts assertions .focus %}

Command Log

Focus the textarea

cy.get('[name="comment"]').focus()

The commands above will display in the command log as:

Command Log focus

When clicking on the focus command within the command log, the console outputs the following:

console.log focus

See also

  • {% url .blur() blur %}
  • {% url .click() click %}
  • {% url cy.focused() focused %}
  • {% url .type() type %}