-2

I am trying to follow various tutorials on the IntersectionObserver API, such as this one.

Adding the sample code into my component's TS file:

const myImg = document.querySelector('.animate-me');

observer = new IntersectionObserver((entry, observer) => {
  console.log('entry:', entry);
  console.log('observer:', observer);
});

observer.observe(myImg);

Gives me an error:

error TS2300: Duplicate identifier 'observer'.

Also, it complains about const myImg = document.querySelector('.animate-me');

A class member cannot have the 'const' keyword.ts(1248)

what am I missing here?

Narm
  • 10,677
  • 5
  • 41
  • 54
Steve
  • 14,401
  • 35
  • 125
  • 230

1 Answers1

1

Regarding the error A class member cannot have the 'const' keyword.ts(1248), you are doing const myImg = ... inside a class. You do not have to have const when you declare it, this should do myImg = document.querySelector('.animate-me');

I think the error error TS2300: Duplicate identifier 'observer'. is because you have a propery called observer and an IntersectionObserver parameter is also called observer.

The following code should work :

myImg = document.querySelector('.animate-me');

observer = new IntersectionObserver((entry, obs) => {
  console.log('entry:', entry);
  console.log('observer:', obs);
});

observer.observe(myImg);
youri
  • 1,140
  • 8
  • 19
  • Are you in an Angular component? – youri Jun 04 '19 at 14:28
  • 1
    yes. i have tried putting this in the constructor, too. but then I get `Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'` – Steve Jun 04 '19 at 14:32
  • 1
    The code should be executed after the view is initialized, I implemented the `AfterViewInit` and put the code into the implementation. This is a working component, could you try this: ```export class AppComponent implements AfterViewInit { private observer: IntersectionObserver; ngAfterViewInit() { const myImg = document.querySelector('.animate-me'); console.log(myImg); this.observer = new IntersectionObserver((entry, observer) => { console.log('entry:', entry); console.log('observer:', observer); }); this.observer.observe(myImg); } }``` – youri Jun 04 '19 at 14:32
  • That seems to work, except it logs to the console on page load in addition to when the image is scrolled into view. – Steve Jun 04 '19 at 14:37
  • 1
    This is because when the page load, your element intersects out of the viewport and when you scroll down, it intersects in of the viewport. – youri Jun 04 '19 at 14:48
  • So, how do I fire something only on entry (when the item enter the viewport)? – Steve Jun 04 '19 at 17:05
  • 1
    Looks like `console.log('intersecting: ', entry[0].isIntersecting);` works – Steve Jun 04 '19 at 18:54