From 8dc810aca34b7e18181c814ee77be6bd089a0dc7 Mon Sep 17 00:00:00 2001 From: Ryan Wu Date: Wed, 27 Jan 2021 22:03:46 +0800 Subject: [PATCH] fix event listener leak and also support custom scroll event --- src/js/aos.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/js/aos.js b/src/js/aos.js index bcf6d5e1..5240da60 100644 --- a/src/js/aos.js +++ b/src/js/aos.js @@ -48,6 +48,8 @@ let options = { // http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 const isBrowserNotSupported = () => document.all && !window.atob; +// current window scroll handler +let currentScrollHandler const initializeScroll = function initializeScroll() { // Extend elements objects in $aosElements with their positions $aosElements = prepare($aosElements, options); @@ -57,12 +59,17 @@ const initializeScroll = function initializeScroll() { /** * Handle scroll event to animate elements on scroll */ - window.addEventListener( - 'scroll', - throttle(() => { - handleScroll($aosElements, options.once); - }, options.throttleDelay) - ); + const eventName = options.customScrollEvent || 'scroll' + + if (currentScrollHandler) { + window.removeEventListener(eventName, currentScrollHandler) + } + + currentScrollHandler = throttle((event) => { + handleScroll($aosElements, event) + }, options.throttleDelay) + + window.addEventListener(eventName, currentScrollHandler) return $aosElements; };