Javascript window animated scrolling

Javascript window animated scrolling

Разработаем следующее: после клика по ссылке будет происходить плавный скролл до элемента на JavaScript. Реализуем это без использования плагинов, сначала при помощи библиотеки jQuery, а затем на чистом JavaScript

Плавный скролл до якоря.

  1. С помощью jQuery .
  2. Для всех ссылок, начинающихся с # .
  3. На чистом JavaScript — метод Element.scrollIntoView() .
  4. На чистом JavaScript — метод Window.scrollBy() .

Сначала в HTML реализуем обычный «грубый» переход к секции, а затем уже добавим jQuery для создания плавности скролла.

Добавим codeid секциям к которым мы хотим выполнять скролл, а ссылкам атрибут codehref в формате code#name . Решетка — означает идентификатор (id), а name — имя идентификатора.

Наш HTML файл получится примерно такой.

Атрибут href указывает к какому элементу необходимо осуществить переход.

1. Плавный скролл с используя jQuery

 $('.scrollto a').on('click', function() < let href = $(this).attr('href'); $('html, body').animate(< scrollTop: $(href).offset().top >, < duration: 370, // по умолчанию «400» easing: "linear" // по умолчанию «swing» >); return false; >); 

Чтобы добавить плавность перехода для необходимого элемента, просто добавьте навигации класс scrollto

Читайте также:  Как задавать ссылки для html

Изменить скорость скролла можно поменяв значение duration

2. Плавный скролл для всех ссылок, начинающихся с #

Для этого мы обратимся к селектору атрибута тега a при помощи ^ — что будет означать, что мы выбираем все ссылки, начинающиеся с # (решётки)

 $('a[href^="#"').on('click', function() < let href = $(this).attr('href'); $('html, body').animate(< scrollTop: $(href).offset().top >); return false; >); 

3. Плавный скролл на чистом JavaScript — метод Element.scrollIntoView()

Будем использовать метод scrollIntoView(). Это стандартный нативный метод JavaScript.

 const smoothLinks = document.querySelectorAll('a[href^="#"]'); for (let smoothLink of smoothLinks) < smoothLink.addEventListener('click', function (e) < e.preventDefault(); const document.querySelector(id).scrollIntoView(< behavior: 'smooth', block: 'start' >); >); >; 

У метода scrollIntoView() есть недостаток.

Если у нас будет навигация position: fixed , то нам необходимо добавить отступ сверху на x-пикселей , т.е. высоту навигации .

Для решения данной задачи отлично подойдёт метод Window.scrollBy() .

4. Плавный скролл на чистом JavaScript — метод Window.scrollBy()

Метод Window.scrollBy() имеет параметр top в котором мы укажем количество пикселей, на сколько нам необходимо прокрутить страницу.

От общей высоты документа отнимем высоту навигации и получим необходимое смещение в пикселях по оси Y .

 document.querySelectorAll('a[href^="#"').forEach(link => < link.addEventListener('click', function(e) < e.preventDefault(); let href = this.getAttribute('href').substring(1); const scrollTarget = document.getElementById(href); const topOffset = document.querySelector('.scrollto').offsetHeight; // const topOffset = 0; // если не нужен отступ сверху const elementPosition = scrollTarget.getBoundingClientRect().top; const offsetPosition = elementPosition - topOffset; window.scrollBy(< top: offsetPosition, behavior: 'smooth' >); >); >); 

Если нужен отступ сверху, укажите class элемента (навигации), чтобы вычислить его высоту. Если не нужен отступ, переменной topOffset присвойте значение 0 .

Источник

animated-scroll-to

Lightweight (1.45kb gzipped) scroll to function with a powerful API. Scrolls window or any other DOM element.

The main difference to other libraries is that it accepts speed of scrolling instead of duration. This way scrolling for 200 pixels will last less than scrolling 10000 pixels. Minimum and maximum duration are configurable and set to reasonable defaults (250 and 3000ms).

All changes are tracked in CHANGELOG.

Demo

Features

  • Accepts speed per 1000px instead of duration
  • Scrolls window or any other DOM element horizontally and vertically
  • Returns a promise with a boolean flag which tells you if desired scroll position was reached (for IE you’ll need to include a Promise polyfill)
  • If called multiple times on the same element, it will cancel prior animations
  • Optionally prevent user from scrolling until scrolling animation is finished

Usage

npm install animated-scroll-to 

and import it in your app

import animateScrollTo from 'animated-scroll-to'; // It returns a promise which will be resolved when scroll animation is finished animateScrollTo(500).then(hasScrolledToPosition =>  // scroll animation is finished // "hasScrolledToPosition" indicates if page/element // was scrolled to a desired position // or if animation got interrupted if (hasScrolledToPosition)  // page is scrolled to a desired position > else  // scroll animation was interrupted by user // or by another call of "animateScrollTo" > >);

Method signatures

Library has three ways to call it:

// "y" is a desired vertical scroll position to scroll to function animateScrollTo(y, options); // "coords" are an array "[x, y]" // Where "x" and "y" are desired horizontal and vertical positions to scroll to // Both "x" and "y" can be null // which will result in keeping the current scroll position for that axis function animateScrollTo(coords, options); // If you pass a DOM element, page will be scrolled to it function animateScrollTo(scrollToElement, options);

Example usage of each method:

// Scrolls page vertically to 1000px animateScrollTo(1000); // Scrolls page horizontally to 1000px but keeps vertical scroll position animateScrollTo([1000, null]); // Scrolls page horizontally too 1000px and vertically to 500px animateScrollTo([1000, 500]); // Scrolls page both horizontally and vertically to ".my-element" animateScrollTo(document.querySelector('.my-element'));

Options

Options with their default values:

const defaultOptions =  // Indicated if scroll animation should be canceled on user action (scroll/keypress/touch) // if set to "false" user input will be disabled until scroll animation is complete cancelOnUserAction: true, // Animation easing function, with "easeOutCubic" as default easing: t => (--t) * t * t + 1, // DOM element that should be scrolled // Example: document.querySelector('#element-to-scroll'), elementToScroll: window, // Horizontal scroll offset // Practical when you are scrolling to a DOM element and want to add some padding horizontalOffset: 0, // Maximum duration of the scroll animation maxDuration: 3000, // Minimum duration of the scroll animation minDuration: 250, // Duration of the scroll per 1000px speed: 500, // Vertical scroll offset // Practical when you are scrolling to a DOM element and want to add some padding verticalOffset: 0, >;

Easing

By default library is using easeOutCubic easing function. You can pass a custom function only considering the t value for the range [0, 1] => [0, 1] .

To make things easier I provided a list of common easing function below:

/* * Easing Functions * https://gist.github.com/gre/1650294 */ const EasingFunctions =  // no easing, no acceleration linear: (t) =>  return t >, // accelerating from zero velocity easeInQuad: (t) =>  return t * t >, // decelerating to zero velocity easeOutQuad: (t) =>  return t * (2 - t) >, // acceleration until halfway, then deceleration easeInOutQuad: (t) =>  return t  0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t >, // accelerating from zero velocity easeInCubic: (t) =>  return t * t * t >, // decelerating to zero velocity easeOutCubic: (t) =>  return (--t) * t * t + 1 >, // acceleration until halfway, then deceleration easeInOutCubic: (t) =>  return t  0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 >, // accelerating from zero velocity easeInQuart: (t) =>  return t * t * t * t >, // decelerating to zero velocity easeOutQuart: (t) =>  return 1 - (--t) * t * t * t >, // acceleration until halfway, then deceleration easeInOutQuart: (t) =>  return t  0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t >, // accelerating from zero velocity easeInQuint: (t) =>  return t * t * t * t * t >, // decelerating to zero velocity easeOutQuint: (t) =>  return 1 + (--t) * t * t * t * t >, // acceleration until halfway, then deceleration easeInOutQuint: (t) =>  return t  0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t > >

Why?

I wasn’t able to find standalone, simple and working solution.

Browser support

Anything that supports requestAnimationFrame and Promise . For Internet Explorer you’ll need to add es6-promise polyfill.

For IE9 and lower, you’ll to provide requestAnimationFrame polyfill.

For IE8 and lower, you’ll need to polyfill Array.forEach as well. Haven’t tested this though.

It is missing

I really tried to keep simple and lightweight. If you are missing something, feel free to open a pull request.

Version 1

I advise you to use v2, as v1 is deprecated. But it is still available on v1 branch and on npm.

Источник

Enable Smooth Scrolling with JavaScript

Hamburger menu

A third-party library used to be required to accomplish simple effects like a smooth scrolling with JavaScript. Those days are history now that JavaScript supports this feature across almost all modern browsers with the built-in window.scrollTo() method.

Why Use Smooth Scrolling?

Put yourself in the user’s position. You click on a web page element, only to find that the screen has suddenly changed and you don’t know what happened or where you are. This abrupt change can be confusing to many users.

Enter smooth scrolling, which JavaScript provides seamlessly. Think of it as a guide. The animation guides you to the desired spot after clicking on a web page element. So now you know where you are and how you arrived there. Overall, it provides a more pleasant and user-friendly experience.

While smooth scrolling is a great feature to have, it can also be easily abused. Make sure that you’re not putting auto-scroll features all over your site where your users wouldn’t expect to have it. Clicking a menu option or button to take a user to a different part of the current page is ideal, but setting auto-scrolls throughout the site to lure them to other places they wouldn’t expect is not.

How to Animate Scrolling with JavaScript

You’re probably already familiar with creating a scroll that automatically jumps to a specific location within a webpage:

The above snippet jumps the user down 1,000 pixels vertically from the top of the web page, just without the animation.

Create a smooth scrolling animation with the following JavaScript syntax:

window.scroll( top: 1000, 
behavior: "smooth"
>);

The second snippet provides the same result as the first, except this time it animates down 1,000 pixels vertically from the top of the web page.

Incremental Scroll

There may be times where you don’t want to scroll to a specific Y position on a web page, but you want to scroll up or down an exact pixel amount.

This is known as incremental scrolling, which you can accomplish this with JavaScript’s window.scrollBy() method:

window.scrollBy( top: -100, 
behavior: "smooth"
>);

Scroll to the Top of the Page

You can scroll to the top of the page by setting the «top» attribute to 0, the first Y position in an HTML page:

window.scrollTo( top: 0, 
behavior: "smooth"
>);

Scroll to the Bottom of the Page

Similarly, you can scroll to the bottom of the page by retrieving the window’s inner height:

window.scrollTo( top: window.innerHeight, 
behavior: "smooth"
>);

Scroll to a DOM Element

This option creates an automatic smooth scrolling animation to an element within the DOM:

document 
.getElementById("orangeable")
.scrollIntoView();

This piece of code looks for the DOM element with ID orangeable, then scrolls to the top portion of that element until it’s in view.

Scrolling Behaviors

There are only two available behavior methods for smooth scrolling with JavaScript:

If you want to jump scroll, you can save yourself the extra code and use the window.scrollTo() method with X and Y values that we discussed earlier.

Browser Support

Smooth scrolling is available for use in most modern browsers. Unfortunately for Apple users, Safari does not support his feature yet, however, there is a polyfill option available that will fill the gap and provide the functionality you’re looking for.

Conclusion

Give smooth scrolling a shot in your next project! It’s great fun to work with, extremely easy to implement, and provides a better overall experience for your users.

Comments

There are no comments yet. Start the conversation!

Источник

Оцените статью