| title | focus |
|---|
Focus on a DOM element.
.focus()
.focus(options){% 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{% 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 same_subject .focus %}
cy.get('[type="input"]').focus()// yields the <textarea> for further chaining
cy.get('textarea').focus().type('Nice Product!').blur().focus() is not implemented like other action commands, and does not follow the same rules of {% url 'waiting for actionability' interacting-with-elements %}.
.focus() is a helpful command used as a shortcut. Normally there's no way for a user to "focus" an element without causing another action or side effect. Typically the user would have to click or tab to this element.
Oftentimes using .focus() directly is more concise and conveys what you're trying to test.
If you want the other guarantees of waiting for an element to become actionable, you should use a different command like {% url .click() click %}.
If there is currently a different DOM element with focus, Cypress issues a blur event to that element before running the .focus() command.
Ensure the element you are trying to call .focus() on is a {% url 'focusable element' https://www.w3.org/TR/html5/editing.html#focusable %}.
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.
Internally Cypress does account for this, and will polyfill the blur events when necessary to replicate what the browser does. Unfortunately the browser will still behave differently when not in focus - for instance it may throttle async events. Your best bet here is to keep Cypress focused when working on a test.
{% requirements focusability .focus %}
{% assertions wait .focus %}
{% timeouts assertions .focus %}
Focus the textarea
cy.get('[name="comment"]').focus()The commands above will display in the Command Log as:
{% imgTag /img/api/focus/get-input-then-focus.png "Command Log focus" %}
When clicking on the focus command within the command log, the console outputs the following:
{% imgTag /img/api/focus/console-log-textarea-that-was-focused-on.png "console.log focus" %}
- {% url
.blur()blur %} - {% url
.click()click %} - {% url
cy.focused()focused %} - {% url
.type()type %}