- 8 CSS & JavaScript Snippets for Adding Scroll Effects to Your Website
- Section by Section by Naoya
- All Indications Say You’re Scrolling by MadeByMike
- You Can Scroll If You Want To by Ryan Mulligan
- The Incredible Shrinking Header by Blake Bowen
- Slide to the Right by Ettrics
- Flying Colors by JP Nothard
- Turning Vertical into Horizontal by SitePoint
- Animate on Scroll by Snik
- Scroll On, Web User
- Related Posts
- Related Topics
- Прокрутка
- Предотвращение прокрутки
- Задачи
- Бесконечная страница
- Анимация элементов при прокрутке страницы. JS-плагины
- Анимация Landing Page. Скроллинг
- Skroll-master
- ScrollTrigger-master
- Add scroll based animations to your site with ease.
- All animations are triggered by classes, so you can take advantage of the power that CSS3 animations give you.
- It’s written in vanilla javascript, so you can use it with any framework.
- It uses the window.requestAnimationFrame method so it doesn’t jack the users scroll. Animations are triggered when the browser is ready for it.
- You define the options inside the HTML attribute, so after you have initialised the ScrollTrigger you don’t have to touch JavaScript again.
- ScrollTrigger offers a range of options, from calling custom JavaScript functions to defining custom offsets and classes.
- You scrolled past this block 0 times.
- ScrollTrigger supports vertical and horizontal scrolling, check out the horizontal demo.
- This block only animates once.
- WOW-master
- t-scroll-master
- delighters-master
8 CSS & JavaScript Snippets for Adding Scroll Effects to Your Website
Scrolling is among the most basic tasks we ask of users. And, judging from the amount of scrolling on websites and apps these days – we’re asking a lot.
Adding scroll-based effects can be a great way to enhance user experience. That is, so long as they don’t interfere with the ability to navigate through long stretches of content. If anything, effects should make things easier and add a bit of flair to the mix.
Here is a collection of scrolling effects and utilities that will wow your visitors and (hopefully) stay out of their way.
- Border Effects
- Cursor Effects
- Flame Effects
- Glassmorphism Effects
- Halftone Effects
- Liquid Effects
- Metallic Effects
- Neumorphic Effects
- Neon Effects
- Noise Effects
- Pattern Effects
- Parallax Effects
- Pixelated Effects
- Repelling Effects
- Shadow Effects
- Skeuomorphic Effects
- Transition Effects
Section by Section by Naoya
Modern webpages are often broken down into multiple content sections – each with its own distinct elements. This handy snippet adds a button (available in a variety of styles) to the bottom of the screen that allows users to click and scroll to the next section down. It uses CSS IDs coupled with jQuery to make the navigation work.
All Indications Say You’re Scrolling by MadeByMike
Scroll indicators have become very popular on content-heavy websites. They communicate how far a user is into a story in an easy-to-digest method. Bonus that this solution is CSS-only.
You Can Scroll If You Want To by Ryan Mulligan
Okay, this snippet isn’t necessarily an effect on its own. But it does serve a purpose. So often, designers utilize full-screen background images and other elements that may make scrolling ambiguous to the user. With that, small items like this animated scroll icon let users know that yes, there is more content down below. It’s not right for every situation, but there are times when it makes sense.
See the Pen CSS Site Scroll Micro Animation by Ryan Mulligan
The Incredible Shrinking Header by Blake Bowen
Sticky headers like this one have become a staple over the years. Why? They can add a ton of user convenience. The ability to navigate to other areas of a site without having to scroll up to the top of the page just makes life easier. As per usual, this example shrinks into a more compact element as you scroll down the page.
See the Pen Scroll Header by Blake Bowen
Slide to the Right by Ettrics
Here’s another take on the sticky header. This time, it’s fine-tuned for a one-page site. The top navigation automatically highlights the current content section and allows users to quickly switch between them.
Flying Colors by JP Nothard
Let’s take a look at another snippet that would be a great fit for one-page sites or a long page with multiple content sections. It uses CSS and a little bit of jQuery to change the background color as you scroll down (and yes, it works in reverse too). You might also want to check out a script that does the same thing, but with gradients.
Turning Vertical into Horizontal by SitePoint
Have you ever wanted your website to scroll horizontally instead of vertically? You can do that without any fancy scripts, of course. But what if you didn’t want a horizontal scroll bar? In that case, you’d need something like this example. It utilizes a script called jInvertScroll, which turns your site into a side-scroller, complete with parallax effects.
Animate on Scroll by Snik
Among the bigger trends these days is animating content as it comes into the viewport. When tastefully done, it can bring attention to each section. But go too far and it becomes more like an online circus act. If you decide to take the plunge, consider this snippet. It’s powered by the AOS (animate on scroll) library.
Scroll On, Web User
Back in the day, the prevailing thought was to avoid scrolling at all costs. Now, social media and smartphones have trained us to cover long expanses with our thumbs (and cursors). So, we might as well make it both fun and useful.
That’s what the snippets above aim to do. They cover a variety of use cases and, for the most part, steer clear of being obtrusive. It’s what building a solid UX is all about.
Related Posts
Related Topics
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.
Прокрутка
Событие прокрутки scroll позволяет реагировать на прокрутку страницы или элемента. Есть много хороших вещей, которые при этом можно сделать.
- Показать/скрыть дополнительные элементы управления или информацию, основываясь на том, в какой части документа находится пользователь.
- Подгрузить данные, когда пользователь прокручивает страницу вниз до конца.
Вот небольшая функция для отображения текущей прокрутки:
window.addEventListener('scroll', function() < document.getElementById('showScroll').innerHTML = pageYOffset + 'px'; >);
Текущая прокрутка = прокрутите окно
Событие scroll работает как на window , так и на других элементах, на которых включена прокрутка.
Предотвращение прокрутки
Как можно сделать что-то непрокручиваемым?
Нельзя предотвратить прокрутку, используя event.preventDefault() в обработчике onscroll , потому что он срабатывает после того, как прокрутка уже произошла.
Но можно предотвратить прокрутку, используя event.preventDefault() на событии, которое вызывает прокрутку, например, на событии keydown для клавиш pageUp и pageDown .
Если поставить на них обработчики, в которых вызвать event.preventDefault() , то прокрутка не начнётся.
Способов инициировать прокрутку много, поэтому более надёжный способ – использовать CSS, свойство overflow .
Вот несколько задач, которые вы можете решить или просмотреть, чтобы увидеть применение onscroll .
Задачи
Бесконечная страница
Создайте бесконечную страницу. Когда посетитель прокручивает её до конца, она автоматически добавляет текущие время и дату в текст (чтобы посетитель мог прокрутить ещё).
Пожалуйста, обратите внимание на две важные особенности прокрутки:
- Прокрутка «эластична». Можно прокрутить немного дальше начала или конца документа на некоторых браузерах/устройствах (после появляется пустое место, а затем документ автоматически «отскакивает» к нормальному состоянию).
- Прокрутка неточна. Если прокрутить страницу до конца, можно оказаться в 0-50px от реальной нижней границы документа.
Таким образом, «прокрутка до конца» должна означать, что посетитель находится на расстоянии не более 100px от конца документа.
P.S. В реальной жизни мы можем захотеть показать «больше сообщений» или «больше товаров».
Основа решения – функция, которая добавляет больше дат на страницу (или загружает больше материала в реальной жизни), пока мы находимся в конце этой страницы.
Мы можем вызвать её сразу же и добавить как обработчик для window.onscroll .
Самый важный вопрос: «Как обнаружить, что страница прокручена к самому низу?»
Давайте используем координаты относительно окна.
Документ представлен тегом (и содержится в нём же), который доступен как document.documentElement .
Так что мы можем получить его координаты относительно окна как document.documentElement.getBoundingClientRect() , свойство bottom будет координатой нижней границы документа относительно окна.
Например, если высота всего HTML-документа 2000px , тогда:
// когда мы находимся вверху страницы // координата top относительно окна равна 0 document.documentElement.getBoundingClientRect().top = 0 // координата bottom относительно окна равна 2000 // документ длинный, вероятно, далеко за пределами нижней части окна document.documentElement.getBoundingClientRect().bottom = 2000
Если прокрутить 500px вниз, тогда:
// верх документа находится выше окна на 500px document.documentElement.getBoundingClientRect().top = -500 // низ документа на 500px ближе document.documentElement.getBoundingClientRect().bottom = 1500
Когда мы прокручиваем до конца, предполагая, что высота окна 600px :
// верх документа находится выше окна на 1400px document.documentElement.getBoundingClientRect().top = -1400 // низ документа находится ниже окна на 600px document.documentElement.getBoundingClientRect().bottom = 600
Пожалуйста, обратите внимание, что bottom не может быть 0 , потому что низ документа никогда не достигнет верха окна. Нижним пределом координаты bottom является высота окна (выше мы предположили, что это 600 ), больше прокручивать вверх нельзя.
Получить высоту окна можно как document.documentElement.clientHeight .
Для нашей задачи мы хотим знать, когда нижняя граница документа находится не более чем в 100px от неё (т.е. 600-700px , если высота 600 ).
Анимация элементов при прокрутке страницы. JS-плагины
На одностраничных сайтах, они же лендинги, стало модно и современно использовать анимацию при прокрутке страницы. И это действительно выглядит эффектно и динамично, когда веб-элементы движутся в такт со скроллингом страницы. Я уже писал пару обзоров на такую тему (тут и тут), но везде было по одному варианту.
Сейчас же хочу поделиться небольшой подборкой из 5-ти плагинов JS, с помощью которых можно реализовать анимация элементов при прокрутке страницы. С подключением плагином проблем быть не должно: всё по стандарту. Ну, то есть, вставляете код в HEDAR или FOOTER, а дальше подставляете нужные классы к нужному элементу. Ниже на примере всё будет ясно.
Анимация Landing Page. Скроллинг
Хочу подчеркнуть, что порядок публикации плагинов, не означает рейтинг их качества. Все они по-своему отличные. Вам просто остаётся сделать выбор.
Skroll-master
JavaScript библиотека с 17 эффектами анимации, применимы для любых элементов на веб-странице. По умолчанию анимация при прокрутке страницы отключена для мобильных устройств. Что очень хорошо, но при желании можно включить.
Подключение
ScrollTrigger-master
Лёгкий и эффектный JS-плагин. Основное использование – запуск классов на основе текущей позиции прокрутки. Можно сказать, полное пользовательское настраивание. К примеру, когда элемент попадает в область просмотра, затемните его или задайте смещение.
Подключение