2

I'm trying to make a horizontal scroll website, but I don't know how to smoothly scroll from one element to the other. I tried the following code:

$("a[href='#top']").click(function() {
  $("body").animate({ scrollTop: 0 }, "slow");
  return false;
});

But it only scrolls to the top, I also tried the jQuery-plugin ScrollTo, but I just can't get it to work, I also tried the jQuery plugin:

$('.click').click(function(){
    $.scrollTo( '.last', 800, {easing:'elasout'});
});

But also without succes.

Does anyone know a good, easy to understand, sample I can use? Thanks in advance!

MattAllegro
  • 6,455
  • 5
  • 45
  • 52
Jay Wit
  • 2,987
  • 7
  • 32
  • 34

2 Answers2

4

untested

   $('.click').click(function(){
        $.scrollTo( $('.last'), 800);
    });
Rafay
  • 30,950
  • 5
  • 68
  • 101
  • If anyone would like to see a demo that uses the jQuery.ScrollTo Plugin he may take a look [at this answer to a similar question](http://stackoverflow.com/questions/17722497/scroll-smoothly-to-specific-element-on-page/17742056#17742056) – surfmuggle Jul 19 '13 at 09:11
4

In case you have to / need to avoid using jQuery here is vanilla JS solution which worked for us nicely:

function scrollToElement(myElement, scrollDuration = 500) {
    const elementExists = document.querySelector(myElement);
    if (elementExists && elementExists.getBoundingClientRect) {
        const rect = elementExists.getBoundingClientRect();
        const elementTop = rect.top + window.scrollY - 200; // a bit of space from top
        var cosParameter = (window.scrollY - elementTop) / 2,
            scrollCount = 0,
            oldTimestamp = performance.now();
        function step(newTimestamp) {
            console.log(scrollCount);
            scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
            if (scrollCount >= Math.PI) {
                window.scrollTo(0, elementTop);
                return;
            }
            window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)) + elementTop);
            oldTimestamp = newTimestamp;
            window.requestAnimationFrame(step);
        }
        window.requestAnimationFrame(step);
    }
}
scrollToElement("#yourElement");

I hope it helps :)

Lukas V
  • 126
  • 1
  • 4