jonaskuske / smoothscroll-anchor-polyfill

⚓ Apply smooth scroll to anchor links, polyfill scroll-behavior
https://jonaskuske.github.io/smoothscroll-anchor-polyfill
MIT License
41 stars 3 forks source link

Smooth scroll on focus change #39

Closed bigskillet closed 2 years ago

bigskillet commented 3 years ago

Curious if it's possible to use smoothscroll-anchor-polyfill with html:focus-within? I'd like to animate the tab/focus similar to Chrome and Firefox usage. The code below is not working. Any ideas?

html:focus-within {
  --scroll-behavior: smooth;
  scroll-behavior: smooth;
}
jonaskuske commented 3 years ago

Hmm, pseudo classes like :focus-within should be supported no problem, I'll give it a try later today to see for myself.

However I'm not sure what you're actually trying to achieve here?

html:focus-within { scroll-behavior: smooth; }

means that as long as some element of the website is focused, clicking on anchors will smoothscroll to their target instead of jumping there. However, if you're clicking on anchor links or generally interacting with the website, then something inside html always has focus so I don't see the advantage of html:focus-within over just html here.

The only time html:focus-within wouldn't match is when you're interacting with the browser UI, another window, DevTools etc. but then you can't click on anchors at the same time so scroll-behavior isn't relevant at that time no matter your CSS.

bigskillet commented 3 years ago

Using :focus-within, I was trying to get the animation to work when tabbing the :focus down the page when html didn't work. I see what you're saying about it being unnecessary, so maybe it's an issue with the tab focus itself and not necessarily the pseudo class?

jonaskuske commented 3 years ago

Ah I see!

Yeah, the :focus-within class doesn't really help here unfortunately. You'd have to detect focus change via tab/shift+tab keypresses (anything else?), intercept the default scroll and smooth scroll instead. That doesn't happen as of now, only hashchange events for forwards/backwards nav are treated this way. Searching for stuff within the page using ctrl+f is another area where browsers with native support will apply smooth scroll, but this script doesn't. Unfortunately it is very tricky to intercept such native browser behavior – the way it currently works for hashchange events is super hacky... I can try if the way it's implemented for hashchange also works for focus navigation, but can't guarantee anything. 😅

jonaskuske commented 2 years ago

I don't see a way to implement this, the Ctrl+F forwards/backwards behavior is internal and can't be observed.