Answer the question
In order to leave comments, you need to log in
Why does the method only work for the last element?
Why does the value scrolled
only change for the last element? querySelectorAll returns all elements, right? Why only works for the latter and how to fix it?
let obj = document.querySelectorAll('h2');
obj.forEach((el) => {
let {top,bottom} = el.getBoundingClientRect();
let height = document.documentElement.clientHeight;
if (top < height && bottom > 0) {
this.scrolled = true
} else {
this.scrolled = false
}
})
Answer the question
In order to leave comments, you need to log in
Works for both elements, just scrolled - you only have one. Therefore, it always takes the value corresponding to the last element - successfully set to true when processing the first element is overwritten by false, which is set when processing the second.
As far as I understand, it should be like this .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question