baptistebriel / smooth-scrolling

smooth scrolling and parallax effects on scroll
MIT License
612 stars 75 forks source link

scrollTo() after resize #108

Closed ivodolenc closed 5 years ago

ivodolenc commented 5 years ago

Hey man, thanks for this awesome lib! 👌

I use it in my new portfolio and everything works great, but I've noticed a little problem with the scrollTo function.

After resizing the window, scrollTo links to the wrong position. I'm guessing that the problem is with caching top point (el.offsetTop) of resized section, it needs an update.

This is my current code:

import Smooth from 'smooth-scrolling'

const section = document.querySelector('.vs-section')
const smooth = new Smooth({
    native: false,
    section: section,
    preload: true,
    noscrollbar: true,
    ease: 0.04
  });

smooth.init();

...and later on

// Section have position relative (inside vs-section)
// Section Hello
var scrollToHello = document.querySelector('.hello').offsetTop;

// Btn is in fixed header (outside vs-section)
// On click -> scrollTo hello section
var siteBtn = document.querySelector('.site-btn');

sitekBtn.addEventListener('click', function(event) {
  TweenLite.to(smooth.vars, 0.7, {
    target: scrollToHello,
    ease: Expo.easeInOut
  });
});

Again, this works great, but after resizing it links to the wrong position. How can I solve this, do you have some idea? 🤔

baptistebriel commented 5 years ago

Glad you like it! How about moving the scrollToHello inside the click function? Instead of getting the top position once, just get the right value on click and no matter how many time you resize your window, once you click it will return the right value.

var siteBtn = document.querySelector('.site-btn');
sitekBtn.addEventListener('click', function(event) {
  var scrollToHello = document.querySelector('.hello').offsetTop;
  TweenLite.to(smooth.vars, 0.7, {
    target: scrollToHello,
    ease: Expo.easeInOut
  });
});
ivodolenc commented 5 years ago

Yeah, that rocks! Thanks for super fast response , I appreciate it. 👍