artemsites
3/23/2022 - 9:28 AM

Как сделать плавный скрол к верху страницы (по нажатию на кнопку) на js (javascript)?

/**
 * @title Scroll to top by click button | Скролл наверх по нажатию на кнопку
 *
 * @dependencies scrollSmoothlyToPosition() - https://gist.github.com/artemijeka/860cfcd079b1f42cace732c31b5e3a29
 * @dependencies commonVariables() - https://gist.github.com/artemijeka/94817ed0212b04d683a1d9e47a897a18
 *
 * @author artemsites.ru
 * @version 1.5 - 11.04.2023
 * @source  https://gist.github.com/artemijeka/44e9fb8a60c57e36d1763490a235ce34
 *
 * @param {String} params.selectorOrNode - селектор кнопки | button selector
 * @param {Boolean} params.init          - инициализация | initialization
 * @param {String} params.toSelector     - [опционально] селектор куда скролим | [optional] where to scroll selector
 **/
 
// Импортировать функцию самого автоскрола | Import the function of the autoscroll itself
import { scrollSmoothlyToPosition } from "@/helpers/scrollSmoothlyToPosition";

// Или обяъвить её перед инициализацией кнопки скролла | Or declare it before initializing the scroll button
import { commonVariables } from "@/helpers/commonVariables";
commonVariables();

export function btnScrollToTop(params) {
  let elToTop = null;
  let targetY = 0;

  if (typeof params.selectorOrNode === "string") {
    elToTop = document.querySelector(params.selectorOrNode);
  } else {
    elToTop = params.selectorOrNode;
  }

  elToTopSetUnsetClasses();
  window.addEventListener("scroll", function () {
    elToTopSetUnsetClasses();
  });

  // if (params.toSelector) {
  //   let target = document.querySelector(params.toSelector);
  //   console.log(target)
  //   if (target) {
  //     targetY = document.querySelector(params.toSelector).getBoundingClientRect().y;
  //     console.log(targetY)
  //   }
  // }

  elToTop.addEventListener("click", function () {
    scrollSmoothlyToPosition({ y: targetY });
  });

  function elToTopSetUnsetClasses() {
    // Если не первая половина экрана то показываем кнопку | If not the first half of the screen then we show the button
    if (window.$common.viewportTopY >= window.$common.viewportHeight / 2) {
      elToTop.classList.remove("--hidden");
    }
    // Если первая половина экрана то скрываем | If the first half of the screen then hide
    else {
      elToTop.classList.add("--hidden");
    }

    // Всегда cкрываем при скроле вниз | Always hide when scrolling down
    if (window.$common.scrollDirection === "down") {
      elToTop.classList.add("--hidden");
    }
  }
}
.btn-to-top { 
	opacity: 1;
	transition: 500ms;
  
	&.--hidden { 
		opacity: 0;
		pointer-events: none;
	}
}

Как сделать плавный скрол к верху страницы (по нажатию на кнопку) на js (javascript)?

Как использовать функцию

import {btnScrollToTop} from 'btnScrollToTop.js';
document.addEventListener('DOMContentLoaded', function(){
  new btnScrollToTop({ selectorOrNode: '.btn-to-top' });
});

Как пользоваться функцией в NuxtJS/VueJS (composition api)

<template>
  <button ref="btnToTop">To top</button>
</template>

<script setup>
import { btnScrollToTop } from '~/helpers/btnScrollToTop';
 
let btnToTop = ref(null);
 
onMounted(() => {
  new btnScrollToTop({ selectorOrNode: btnToTop.value });
});
</script>

Кнопке необходимо добавить стили на селектор .--hidden

.btn-to-top {
  opacity: 1; 
  transition: 500ms; 
  
  &.--hidden {
    opacity: 0;
    pointer-events: none;
  }
}

Зависимости которые необходимо добавить

scrollSmoothlyToPosition() - https://gist.github.com/artemijeka/860cfcd079b1f42cace732c31b5e3a29
commonVariables() - https://gist.github.com/artemijeka/94817ed0212b04d683a1d9e47a897a18

Как сделать плавный скрол к верху страницы (по нажатию на кнопку) на js (javascript)?

Обычно это кнопка появляющаяся для быстрого (плавного) перехода к верху страницы

Сама функция скролла к верху страницы по нажатию на кнопку

How to make a smooth scroll to the top of the page (by clicking on the button) in js (javascript)?

How to use the function

import {btnScrollToTop} from 'btnScrollToTop.js';
document.addEventListener('DOMContentLoaded', function(){
  new btnScrollToTop({ selectorOrNode: '.btn-to-top' });
});

How to use the function in NuxtJS/VueJS (composition api)

<template>
  <button ref="btnToTop">To top</button>
</template>

<script setup>
import { btnScrollToTop } from '@/helpers/btnScrollToTop';
 
let btnToTop = ref(null);
 
onMounted(() => {
  new btnScrollToTop({ selectorOrNode: btnToTop.value });
});
</script>

The button needs to add styles to the selector .--hidden

.btn-to-top {
  opacity: 1; 
  transition: 500ms; 
  
  &.--hidden {
    opacity: 0;
    pointer-events: none;
  }
}

Dependencies that need to be added

scrollSmoothlyToPosition() - https://gist.github.com/artemijeka/860cfcd079b1f42cace732c31b5e3a29
commonVariables() - https://gist.github.com/artemijeka/94817ed0212b04d683a1d9e47a897a18

How to make a smooth scroll to the top of the page (by clicking on the button) in js (javascript)?

This is usually a button that appears for a quick (smooth) transition to the top of the page

The function itself scrolls to the top of the page by clicking on the button