How can you achieve a smooth movement to the anchor, without the participation of third-party libraries? It turns out to be realized only from the top point to the right one, well, if not from the top, everything is no longer correct, and from the bottom up, I won’t even apply how to do it.

var top = 0; var scr = setInterval(function () { top += 10; window.scrollTo(0, top); if(top > coords.top ){ clearInterval(scr); } }, 15); 
  • window.scrollY will prompt the current screen position. The algorithm is trivial. I can not imagine what else could be the problem. - Arnial
  • can be viewed in the direction of the function scrollIntoView - Grundy
  • @Grundy if you use it, then what about the animation? - Roman Fedorov
  • @RomanFyodorov, what is meant by animation in this context? - Grundy
  • @Grundy well, that would gradually descend, and not immediately, as shown above used setInterval - Roman Fedorov

1 answer 1

Just developing your code:

 var myScroll = function(to){ var currentScroll = window.scrollY, down = currentScroll < to; //вниз крутим или вверх var scr = setInterval(function () { currentScroll = currentScroll + 10 * (down ? 1 : -1); window.scrollTo(0, currentScroll); if((down && currentScroll > to) || (!down && currentScroll < to)){ clearInterval(scr); } }, 15); } 

Use: myScroll(600) .

But I do not consider it a good idea to use the interval here, and I would generally be repelled by the duration of the animation and count the number of steps and their frequency.

Instead of setInterval, I’m used to using a more secure option.

 setTimeout(function(){ //do something if(continue){ setTimeout(arguments.callee, 20); } }, 20); 

although in this case, I confess, I don’t see any difference with setInterval.

I usually went about another way when creating animation: I took the argument as the duration of the animation, divided it by the duration of one frame (20ms, for example) and also divided the change in the parameter being animated. Thus, I calculated how much one parameter needs to be changed and how many iterations it takes. I set the timers to 20ms and made changes to them by the calculated value.

It's useful now to find an indicative code and found an article about creating animation that I had never met before. At first glance, it is very interesting: https://learn.javascript.ru/js-animation

  • Thank you, not badly implemented, if not difficult then in a nutshell how would you do better, mb something will come to mind. - Roman Fedorov
  • @ Roman Fedorov added the answer. maybe find something interesting. - Ivan Pshenitsyn