Files
cypress/docs/source/api/commands/focus.md
2017-06-09 14:04:20 -04:00

2.8 KiB

title, comments
title comments
focus true

Focus on a DOM element.

Syntax

.focus()
.focus(options)

Usage

.focus() requires being chained off another cy command that yields a DOM element.

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

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

{% fa fa-exclamation-triangle red %} Invalid 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 Notes
log true Whether to display command in Command Log

Yields

.focus() yields the new DOM element that was focused.

Timeout

.focus() will continue to try to focus the element for the duration of the defaultCommandTimeout.

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 focusable element. Most commonly, you'll want to ensure that the element is not disabled, although there are other factors.

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.

Command Log

Focus the textarea

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

The commands above will display in the command log as:

screen shot 2015-11-27 at 1 32 37 pm

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

screen shot 2015-11-27 at 1 33 00 pm

See also

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