K
K
Kryptonit2020-05-13 21:35:28
JavaScript
Kryptonit, 2020-05-13 21:35:28

How to make smooth scrolling to anchor?

I used this jq code:

$('a[href^="#"]').click(function(){
        var target = $(this).attr('href');
        $('html, body').animate({
            scrollTop: $(target).offset().top
        }, 500);
    });

In general, it is working, but before each anchor it spins at a different speed, because. for everything about everything 0.5 sec, if someone has improved analogs, please share, I want what would happen like on this site:
https://ru.wix.com/website-template/view/html/1885.. .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
iBird Rose, 2020-05-13
@iiiBird

school mathematics course. S = v * t
you need the same speed (v), so you need to select the correct time (t, which you will enter into the animate function) depending on the path (S).
in total we get the formula t = S/v;
so you are looking for a path from the current scrollTop to the offset().top of your element - this will be (S).
well, you already select the speed by poking.

F
Froggyweb, 2020-05-13
@Froggyweb

If in Jquery, then something like this

$('a[href*="#"]').click(function(e) {
  const $target = $(this.hash);
  const topOffset = 100;
  if ($target.length) {
    e.preventDefault();
    $("html, body")
      .stop()
      .animate(
        {
          scrollTop: $target.offset().top - topOffset
        },
        900,
        "swing",
        function() {
          history.pushState(
            {},
            document.title,
            window.location.pathname + target
          );
          return false;
          // window.location.hash = target;
        }
      );
  }
});

P
Pavel Lovtsevich, 2020-05-14
@lautsevich

It may be enough for you to get by with CSS (scroll-snap property set) if browser support suits. A few articles on the topic:

  • Smart scrolling with Scroll Snap Points
  • CSS Scroll Snapping
  • Well-Controlled Scrolling with CSS Scroll Snap

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question