Smooth Scrolling

Используя только нативный JS

  1. // Scroll to specific values
  2. // scrollTo is the same
  3. window.scroll({
  4. top: 2500,
  5. left: 0,
  6. behavior: 'smooth'
  7. });
  8.  
  9. // Scroll certain amounts from current position
  10. window.scrollBy({
  11. top: 100, // could be negative value
  12. left: 0,
  13. behavior: 'smooth'
  14. });
  15.  
  16. // Scroll to a certain element
  17. document.querySelector('.hello').scrollIntoView({
  18. behavior: 'smooth'
  19. });

Используя jQuery

  1. // Select all links with hashes
  2. $('a[href*="#"]')
  3. // Remove links that don't actually link to anything
  4. .not('[href="#"]')
  5. .not('[href="#0"]')
  6. .click(function(event) {
  7. // On-page links
  8. if (
  9. location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
  10. &&
  11. location.hostname == this.hostname
  12. ) {
  13. // Figure out element to scroll to
  14. var target = $(this.hash);
  15. target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  16. // Does a scroll target exist?
  17. if (target.length) {
  18. // Only prevent default if animation is actually gonna happen
  19. event.preventDefault();
  20. $('html, body').animate({
  21. scrollTop: target.offset().top
  22. }, 1000, function() {
  23. // Callback after animation
  24. // Must change focus!
  25. var $target = $(target);
  26. $target.focus();
  27. if ($target.is(":focus")) { // Checking if the target was focused
  28. return false;
  29. } else {
  30. $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
  31. $target.focus(); // Set focus again
  32. };
  33. });
  34. }
  35. }
  36. });