I have continuous animation, made with gsap library. I'm using mouseover
/mouseout
events to pause/resume this animation. On window resize event I'm making re-initialization. My question is: do I need to call removeEventListener
on 2nd initialization?
Here is the code/scenario:
const scroll = {
create: function (el) {
this.scrollAnimation = gsap.timeline({
repeat: -1
});
// another piece of awesome code here...
this.create__addMouseEvents(el);
},
create__addMouseEvents: function (el) {
// here, on window resize event( when i call update(), during re-initialization ), do i need to call "removeEventListener"?
el.addEventListener('mouseover', () => this.scrollAnimation.pause());
el.addEventListener('mouseout', () => this.scrollAnimation.resume());
},
update: function () {
//
// destroy old "scrollAnimation" if it's already exists
if (this.scrollAnimation) {
this.scrollAnimation.kill();
}
//
// reinit
this.init();
},
init: function () {
// some awesome code here...
this.create(el);
}
}
document.addEventListener('DOMContentLoaded', function () {
scroll.init();
});
let windowResizeTimer;
window.addEventListener('resize', function () {
clearTimeout(windowResizeTimer);
windowResizeTimer = setTimeout(function () {
scroll.update();
}, 150);
});
you are currently adding a new event to the browser with every update. A simple solution would be the following:
Since you are not instantiating the scroll object, you have to change the global reference scroll.eventsAlreadyAdded.
Alternatively, you can slightly rewrite the code so that you are working on a instantiated variable (not tested):