Javascript scroll event problem

Hi everyone,
iam trying to add class to my element when iam at specific point in scroll but i dont want a fix value for that rather than i want it a variable so that screen dont matters, itried to achive this but wont work, kindly help.
thanks in advance
pen is----
https://codepen.io/gurpreet_singh9189825/pen/vYyRVMN

const body = document.querySelector('body');
const div = document.querySelector('.container');

console.log(window.innerHeight)

document.addEventListener('scroll', () => {
  if (window.scrollY > window.innerHeight) {
    div.classList.add('test')
  }
})

This adds a class to a div once you have scrolled further than the length of the window.

Sorry, I for got to remove some testing code.

hi, thanks.but this not working as i want, i want it to add class active when scroll reaches the container so the animation work

What I showed you was some tools that may help, what you need to do is essentially say: when the elements are in view do this.

but its not working element is not coming in the view say if my container is 456px from the body top then when scroll reach container top then it should add class but it is adding class when i scroll past the container.

Not sure if I understand your question but using the Intersection Observer API might be an option.

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

no… i was looking for vanilla javascript

It is plain JS. It’s using a browser API.

ok i was not aware of this, couldn’t this will achieve through DOM ?

It is using the DOM. I would suggest you read the MDN article and watch the video.

Here are two more articles.


If you just search for intersection observer api you will get a bunch of articles and videos you can look at. I know it looks super complicated (and to be fair it is a bit) but it’s really not as bad as it looks at first.