1

I am somewhat new to JS, and I've run into an error I am unable to resolve while using Intersection Observer.

Here is the code I am attempting to use:

const header = document.querySelector("navBarContainer");
const imageHeader = document.querySelector("myImageHeader");

const imageHeaderOptions = {
  rootMargin: "-50px 0px 0px 0px"
};

const imageHeaderObserver = new IntersectionObserver(function(
  entries,
  imageHeaderObserver
) {
  entries.forEach(entry => {
    if (!entry.isIntersecting) {
      header.classList.add("scrolled");
    } else {
      header.classList.remove("scrolled");
    }
  });
},
imageHeaderOptions);

imageHeaderObserver.observe(imageHeader);
  • The root cause is most likely [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Samathingamajig Jun 30 '22 at 21:34

1 Answers1

1

the Intersection Observer can only observe HTML elements that actually exist in the DOM. By looking at your code, the way you are using the querySelector is incorrect. If you are trying to select an HTML element by class using the querySelector, you should use the same syntax you would use in CSS. E.g. HTML: <header class="myImageHeader"></header> JS: const imageHeader = document.querySelector(".myImageHeader")

Hope this solves your issue man.