0

I am still trying to make friends with Javascript so am i with the Intersection Observer API. I have three target elements that am monitoring their visibility in the device's viewport:

    let $target_1 = section1.querySelector('.about-me');
    let $target_2 = section1.querySelector('.background');
    let $target_3 = section1.getElementsByClassName('content');

And this is the declaration of the observer:

 let settings = {
     root: null,
     threshold: 0.15
 }

 let observer = new IntersectionObserver((entries) => {
     entries.forEach((entry) => {
         if(entry.intersectionRatio >= 0.15) {
             $target_1.classList.add('slide-in');
            
         }
     });
 }, settings);

Then to observe my targets:

 observer.observe($target_1);
 observer.observe($target_2);
 observer.observe($target_3);

So far, I believe that when any of my targets is 15% (0.15) visible in the viewport, the callback function (passed as first argument in the instance of 'IntersectionObserver' call), will be invoked. My problem is that, whenever the callback function is invoked, it will always add the 'slide-in' class to only the '$target_1' element. What i want is that, the 'slide-in' class should be added to the currently observed target. Just something like

 e.currentTarget.classList.add('slide-in') 
.

I do not want to create many instances of Intersection Observer to watch my targets, i.e,

 let observer = new IntersectionObserver( callback, options );
 let observer2 = new IntersectionObserver( callback, options );
 let observer3 = new IntersectionObserver( callback, options );

Is there a way that i can get to access the currently observed target element?

hane Smitter
  • 516
  • 3
  • 11

1 Answers1

1

It's actually very simple and alike you access the target from event.

Look at the code below, I've just changed how you access element from $target_1 variable to entry from the function argument.

entry.target.classList.add('slide-in');

And here is the whole code:

 let settings = {
     root: null,
     threshold: 0.15
 }

 let observer = new IntersectionObserver((entries) => {
     entries.forEach((entry) => {
         if(entry.intersectionRatio >= 0.15) {
             entry.target.classList.add('slide-in');
            
         }
     });
 }, settings);
Terminat
  • 1,199
  • 5
  • 21