惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
PCI Perspectives
PCI Perspectives
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
S
Secure Thoughts
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
WordPress大学
WordPress大学
SecWiki News
SecWiki News
B
Blog
小众软件
小众软件
Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
LINUX DO - 热门话题
Recent Commits to openclaw:main
Recent Commits to openclaw:main
酷 壳 – CoolShell
酷 壳 – CoolShell
IT之家
IT之家
The Cloudflare Blog
Google DeepMind News
Google DeepMind News
Know Your Adversary
Know Your Adversary
Y
Y Combinator Blog
F
Fortinet All Blogs
W
WeLiveSecurity
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Last Week in AI
Last Week in AI
The Last Watchdog
The Last Watchdog
S
Schneier on Security
爱范儿
爱范儿
V
V2EX - 技术
L
LINUX DO - 最新话题
月光博客
月光博客
博客园 - 【当耐特】
Latest news
Latest news
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
U
Unit 42
Schneier on Security
Schneier on Security
E
Exploit-DB.com RSS Feed
J
Java Code Geeks
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
TaoSecurity Blog
TaoSecurity Blog
博客园 - 叶小钗
T
Troy Hunt's Blog
大猫的无限游戏
大猫的无限游戏
AI
AI
Security Latest
Security Latest

Matthias Ott

Hello Again, World This, Still Not for Everyone The Shape of Friction WeissKlang L1 – Punching Above Its Weight Continvoucly Morged Value Webspace Invaders To Affinity and Beyond The Mystery of Storytelling Amateurs! Echoes of Connection Linear() Is Not (That) Linear View Transitions: The Smooth Parts Adding AVIF and WebP Support to My Craft CMS Site Challenge Acoustic Room Treatment and Building Sound Panels, Part 1: Planning Play On Overshoot The HTML Output Element Listening Closely Compressed Fluid Typography The Lifeblood of the Web What Could Go Wrong? That’s My Rank Making Space CSS :is() :where() the Magic Happens Visual Regression Testing for External URLs With Playwright Jane Goodall’s Famous Last Words European Tech Alternatives 🇪🇺 Independent Type Foundry Advent Calendar – Day 24: NaN Independent Type Foundry Advent Calendar – Day 23: Typotheque Independent Type Foundry Advent Calendar – Day 22: 205TF Independent Type Foundry Advent Calendar – Day 21: HvD Fonts Independent Type Foundry Advent Calendar – Day 20: Frere-Jones Type Independent Type Foundry Advent Calendar – Day 19: Fontwerk Independent Type Foundry Advent Calendar – Day 18: Vectro Independent Type Foundry Advent Calendar – Day 17: Studio René Bieder Independent Type Foundry Advent Calendar – Day 16: R-Typography Independent Type Foundry Advent Calendar – Day 15: David Jonathan Ross Independent Type Foundry Advent Calendar – Day 14: Interval Type Independent Type Foundry Advent Calendar – Day 13: Newglyph Independent Type Foundry Advent Calendar – Day 12: Swiss Typefaces Independent Type Foundry Advent Calendar – Day 11: Sharp Type Independent Type Foundry Advent Calendar – Day 10: Colophon Foundry Independent Type Foundry Advent Calendar – Day 9: Commercial Type Independent Type Foundry Advent Calendar – Day 8: Letters from Sweden Independent Type Foundry Advent Calendar – Day 7: Lineto Independent Type Foundry Advent Calendar – Day 6: Ohno Type Company Independent Type Foundry Advent Calendar – Day 5: Milieu Grotesque Independent Type Foundry Advent Calendar – Day 4: TypeMates Independent Type Foundry Advent Calendar – Day 3: Klim Type Foundry Independent Type Foundry Advent Calendar – Day 2: Dinamo Independent Type Foundry Advent Calendar – Day 1: Grilli Type The Independent Type Foundry Advent Calendar 2022 A Conversation With ChatGPT ChatGPT, please explain websites in the words of William Shakespeare Transient Frameworks Leaving Twitter Behind Converting Your Twitter Archive to Markdown The Wrong Question It Wasn’t Written Syndicating Posts from Your Personal Website to Twitter and Mastodon Suspension None of Your Business Doing Our Part Patch That Package Brain Dump Generating Accessibility Test Results for a Whole Website With Evaluatory The CSS Cascade, a Deep Dive Updates About Updates How to Delete Your Commit History in Git Unblocking Your Writing Blocks, Part 2: I’m Not an Expert nor a “Thought Leader” Connections No Wrong Notes Better Options Design Debt Finite and Infinite Games Don’t Assume, Validate. Necessity Is the Ultimate Teacher One Egg Go Deep There Is No Secret Code Balancing Risk Blue Eyes, Brown Eyes The Shortcut Boomerang My RSS Feed Collection of Personal Websites Frequency The Illusion of Control The Decisions Journey Write It Down Nownownow Into the Personal-Website-Verse Considering the Opposite What is it for? Unlimited Bowling. Never done. We Are Team Internet. We Need to Save #NetNeutrality. Progressive Search Data loss (also) by JavaScript Books I Will Definitely Maybe Read in 2017 Starting to Write Notes
Scrolling Elements Into View
Matthias Ott · 2020-07-15 · via Matthias Ott

Although you should not mess with scrolling unless it is really necessary, scrolling an element into view is something that is needed from time to time. In my case, I recently wanted to scroll to the top of a table after a user clicked on the pagination underneath the table. One way to scroll to an element is to use the good old anchor link. While this is by far the most reliable and resilient option to scroll an element into view, it is not always possible and you have to rely on a bit of JavaScript instead. For a long time, the most reliable way to do this was to use jQuery and scroll the body to the top offset of the element you want to scroll into view:

$('html, body').scrollTop($(element).offset().top);

If you want to have a smooth scroll animation as well, you could use jQuery’s animate() function like so:

$('html, body').animate({
    scrollTop: $(element).offset().top
}, 500);

Here is a Codepen for this example:

See the Pen Scroll Into View – with jQuery by Matthias Ott (@matthiasott) on CodePen.

A Native, Modern Solution #

While you could still do it that way, times have changed and modern browsers now come with native behaviors that can provide better alternatives to jQuery or other third-party scripts. This lets you save one dependency and, in the case of animate(), you might even end up with superior browser performance.

One way to scroll an element into view with native browser APIs is to rewrite the jQuery solution above so that it only uses element properties available in the browser:

// Get the size and position of our element in the viewport
var rect = element.getBoundingClientRect();
// The top offset of our element is the top position of the 
// element in the viewport plus the amount the body is scrolled
var offsetTop = rect.top + document.body.scrollTop;
// Now we can scroll the window to this position
window.scrollTo(0, offsetTop);

As you can see, we have achieved the same result with only three lines of code and both Element.getBoundingClientRect() and Window.scrollTo() have full browser support. But one thing is still missing: The animation. There are two ways we can add smooth scrolling to this solution. The first is to use the native CSS feature scroll-behavior:

html {
  scroll-behavior: smooth;
}

Again, have a look at the Codepen for this example:

See the Pen Scroll Into View – with CSS scroll-behavior: smooth by Matthias Ott (@matthiasott) on CodePen.

Nice! Still no need to mess around with JavaScript animations and we have a robust, progressively enhanced solution. Setting scroll-behavior to smooth will also work for anchor links, by the way. There is only one caveat: Some browsers, like Internet Explorer and Safari, don’t support scroll-behavior yet.

So if you want to support those browsers, too, you might want to use element.scrollIntoView instead:

element.scrollIntoView({ behavior: 'smooth' });

Browser support for scrollIntoView is good, but a few browsers like – you guessed it – IE and Safari don’t support the smooth behavior option. But fear not, there is a polyfill available that adds this functionality to those browsers.

Play around with this Codepen if you like:

See the Pen Scroll Into View – with element.scrollIntoView by Matthias Ott (@matthiasott) on CodePen.

There is one more interesting option to achieve our scroll into view, and that is using the Greensock Animation Platform, aka GSAP, a JavaScript animation library. Let’s say you want to use hardware-accelerated animations in other corners of your site, too, then it can be a good idea to use GSAP to handle the scrolling as well. For one, you can stick to one solution and don’t have to jump from GSAP to element.scrollIntoView and back, but you will also be able to use a timeline in GSAP and easily combine the scroll animation with other animations.

The scroll position of the window can be animated in Greensock with the help of the ScrollToPlugin:

gsap.to(window, {duration: 0.75, scrollTo: element});

Another advantage of using Greensock is that you have more control over the animation timing and the easing functions, meaning the style of animation, and can make your animation really smooth and fine-tune it to your needs.

gsap.to(window, {
    duration: 1.2,  ease: "power4.inOut", scrollTo: element
});

Here, we are using a slightly slower animation with a nice, soft easing curve. Play around with this Codepen to try how the animation feels. If you are unsure which easing functions are available in GSAP, try the Ease Visualizer.

See the Pen Scroll Into View – with Greensock (GSAP) by Matthias Ott (@matthiasott) on CodePen.

What about A11y? #

Depending on how much you scroll around, scroll around, scroll up, scroll up, and scroll down on the site, you will have to make sure that keyboard users don’t get lost. If you change the scroll position via JavaScript, keyboard focus might still not be updated. So when the user starts to navigate again, the site jumps back to where it was before you triggered the scrolling. Heather Migliorisi has written a nice post for CSS-Tricks about what to look for to make sure you build an accessible solution.

Another problem can be that people with a vestibular disorder can get sick when a site moves around too fast. And while those people can opt-out of playing video games that could become dangerous for them, visiting your site should not trigger motion sickness or an epileptic fit. One solution with good browser support is the prefers-reduced-motion media query (1, 2):

html {
  scroll-behavior: smooth;
}

@media (prefers-reduced-motion) {
  html {
	  scroll-behavior: auto;
	}
}

If you want the learn more about designing web animations for motion sensitivity, Val Head has written an excellent post for A List Apart.

And that’s it for today. If you have found other or even better ways to scroll an element into view, let me know. And if you found this post interesting, share it with your friends.

-

This is the 39th post of my 100 days of writing series. You can find a list of all posts here.

~

11 Webmentions

1 Repost

8 Likes

ⓘ Webmentions are a way to notify other websites when you link to them, and to receive notifications when others link to you. Learn more about Webmentions.