Skip to content

fr(cdk/a11y/cdkFocusTrap): Option (or always) not to scroll to element when returning focus #18956

Open
@karptonite

Description

@karptonite

Feature Description

When cdkTrapFocus returns focus to the previously focused element (with cdkTrapFocusAutoCapture set to true), the directive calls .focus() on the previous element. On focus, the browser will, by default, scroll to the focused element. this is not always desirable. I'm not actually certain it is ever desirable, but I don't know all of the use cases for focus trap.

Use Case

Consider an interactive modal or popover that can be opened by a hover event on desktop. It is possible that the previously focused element was off screen. Then, when the modal is closed, the window will be scrolled back to the previously focused element when focus() is called on it.

Here is a simple alternative to calling focus() that would return focus without scrolling:

public focusWithoutScrolling(element: HTMLElement) {
    const x = window.scrollX;
    const y = window.scrollY;
    element.focus({ preventScroll: true });
    //this is necessary because not all browsers yet respect preventScroll
    this.window.scrollTo(x, y);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: cdk/a11yfeatureThis issue represents a new feature or feature request rather than a bug or bug fix

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions