baptistebriel / smooth-scrolling

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

Is there an update-function? #87

Closed 23d1 closed 6 years ago

23d1 commented 6 years ago

Is there any way to update the smooth-scroll after an ajax/pjax-load? Resizing works, but not by simply loading new content within the section...

I tried destroying to the reinitialize on new page but when trying to use Smooth.destroy() I get this;

Uncaught TypeError: smooth_scrolling__WEBPACK_IMPORTED_MODULE_3__.default.destroy is not a function
    at Object.<anonymous> (index.js:423)
    at Object.trigger (barba.js:929)
    at Object.onStateChange (barba.js:1391)
    at Object.goTo (barba.js:1198)
    at Object.onLinkClick (barba.js:1302)
23d1 commented 6 years ago

Nevermind! I had messed up my const declaration, so it was private. .resize() works for this purpose. :)

23d1 commented 6 years ago

Actually, the issue now is I have stickies that I want to offset to the scroll value, which works on page load, but the stickies don't get updated when replacing content with ajax (unless I constantly loop through the querySelectorAll on the callback, which feels excessive). Any ideas?

baptistebriel commented 6 years ago

Hi @23d1,

Initializing/destroying a new instance of smooth for each page can be a solution. There should be a destroy function; if you get this error it's probably an issue when importing the module. Otherwise, you can indeed just call resize() when new content is added/updated.

Yup, you'll need to update the variables corresponding to your elements, the stickies in this example. Once your content has been replaced with ajax, you can call querySelectorAll. Instead of calling this on each frame in the callback, just call it once.

import Smooth from 'smooth-scrolling'

let stickies = document.querySelectorAll('.vs-stickies')

const callback = (scrollY) => {
  if (!stickies) return
  // do stuff
}

const section = document.querySelector('.vs-section')
const smooth = new Smooth({
  native: true,
  section: section,
  callback: callback,
  ease: 0.1
})

smooth.init()

// once the content has been updated with ajax
const update = () => {
  stickies = document.querySelectorAll('.vs-stickies')
  smooth.resize()
}

Let me know if it makes sense!

23d1 commented 6 years ago

@baptistebriel ah yes, of course! Makes much more sense to wrap the querySelector in a function that fires once.