0

I'm trying to implement parallax with intersectionObserver API which calls eventListener scroll function with callback. The problem is what I want to pass parameter "entry.target" to add and removeEventListener functions, is it possible to remove event listener callback with parameter?. Currently I have:

const parallaxScroll = trg => {
   trg.style.top = `${-trg.getBoundingClientRect().top / 7.3}px`;
}

const addParallax = ([entry]) => {
    if(entry.isIntersecting){
       window.addEventListener('scroll', parallaxScroll);

       //what I want to:
       window.addEventListener('scroll', parallaxScroll(entry.target));
    }else{
       window.removeEventListener('scroll', parallaxScroll);

       //what I want to:
       window.removeEventListener('scroll', parallaxScroll(entry.target));
    }
}
1
  • When do you call addParallax? If many times, then don't you risk to create many event handlers for scroll that all get executed on a scroll event? Commented Jun 5, 2021 at 21:23

1 Answer 1

1

You would need to create a wrapper function (or call .bind to do the same) for each parameter. Assuming that you can have several entry objects that each could have an associated active scroll-listener, but not more than one per entry, you could dedicate a property of entry for storing that listener reference:

const addParallax = ([entry]) => {
    if(entry.isIntersecting) {
       if (entry.listener) return; // already have an active listener for this entry
       entry.listener = () => parallaxScroll(entry.target);
       window.addEventListener('scroll', entry.listener);
    } else {
       window.removeEventListener('scroll', entry.listener);
       entry.listener = null;
    }
}

Or with .bind:

const addParallax = ([entry]) => {
    if(entry.isIntersecting) {
       if (entry.listener) return; // already have an active listener for this entry
       entry.listener = parallaxScroll.bind(null, entry.target);
       window.addEventListener('scroll', entry.listener);
    } else {
       window.removeEventListener('scroll', entry.listener);
       entry.listener = null;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Can you please explain how to do this with .bind?
Added the .bind variant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.