algolia / algolia/autocomplete

Autocomplete box doesn't work with fixed positioning

Open
#1,199 1 comment 1 reaction 0 assignees View on GitHub
Dominant language
TypeScript
Stars
5.3k
Forks
341
Avg merge
3d 1h
Merged PRs (30d)
5

Description

## Description

When the search field has fixed positioning on the page and you scroll while the autocomplete box is open the box doesn't follow scroll. The box scrolls out of view.
Related code is here:
https://github.com/algolia/autocomplete/blob/5fd58f6f9cdb6d3dc7ba02eb4b9e985f5e10d8f4/packages/autocomplete-js/src/getPanelPlacementStyle.ts#L25

The problem is that autocomplete uses absolute positioning. To fix this, I suggest to have a configuration to allow it to use fixed positioning instead.

In my project, I was able to work around this issue by doing the following:
* CSS
```css
:root {
--position-autocomplete-panel-top: 52px;
}

.aa-Panel {
position: fixed;
top: var(--position-autocomplete-panel-top) !important;
z-index: 1000;
}
```
* JS
```javascript
const fixPosition = () => {
const rect = document.querySelector('.search-field').getBoundingClientRect();
// Set css variable to be below the search box in case the search box moved when the window was resized
setCSSVar('--position-autocomplete-panel-top', `${rect.bottom}px`);
};

document.querySelector('.aa-Input').addEventListener('focus', fixPosition);
document.querySelector('.aa-Input').addEventListener('blur', fixPosition);
window.addEventListener('resize', fixPosition);
```

## Reproduction
My Sandbox: https://codesandbox.io/s/youthful-microservice-6km8p4?file=/style.css:843-880

**Steps**
1. Add this change to the css of the sandbox:
```css
#autocomplete {
position: fixed;
}
```
2. Now see that the search field follows you while you scroll in the frame
3. When you click in the search field then scroll you will see weird behavior. See screenshot below:
![image](https://github.com/algolia/autocomplete/assets/2372994/579c93ef-8b73-4bae-a632-7959e78c6ad3)

## Expected behavior
It should be possible to make fixed positioning work without a CSS hack using !important.

## Environment

- OS: macOS
- Browser: Chrome
- Autocomplete version: 1.11.1

Contributor guide

Open the contributing guide

Research direction

Start with packages/autocomplete-js/src/getPanelPlacementStyle.ts at the linked lines, then reproduce the behavior using the linked CodeSandbox and its fixed-position CSS change. Determine how fixed positioning should be supported without the !important CSS workaround, and verify that the autocomplete panel remains correctly positioned while scrolling and resizing.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.