X
X
xutegino2017-09-14 00:01:10
JavaScript
xutegino, 2017-09-14 00:01:10

Why does the method only work for the last element?

Why does the value scrolledonly 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
        }
      })

https://codepen.io/kodej/pen/RLNGqe

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-09-14
@xutegino

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 question

Ask a Question

731 491 924 answers to any question