Home > Software design >  element.getBoundingClientRect is not a function
element.getBoundingClientRect is not a function

Time:12-12

const elementsFadeIn = document.querySelectorAll(".fade-in");
window.addEventListener("scroll", fadeIn);
function fadeIn() {
  for (i in elementsFadeIn) {
    let element = elementsFadeIn[i];
    let viewElement = element.getBoundingClientRect().top - window.innerHeight   20;
    if (viewElement < 0) {
        element.classList.add("view-element");
    } 
    else {
        element.classList.remove("view-element");
    }
  }
}

.fade-in {
    transform: translateY(50px) translateZ(0);
    transition-delay: 0.7s;
    transition: 1s;
    opacity: 0;
}
  
 .view-element{
   opacity: 1;
   transform: translateY(0px) rotate(0deg) translateZ(0);
}

why it said that element.getBoundingClientRect is not a function. here is my js and css code. i really don't know what to do.

CodePudding user response:

For...in is for objects. You need to use for loop for arrays.

CodePudding user response:

Try this:

function fadeIn() {
    const elementsToFade = document.querySelectorAll(".fade-in");
    elementsToFade.forEach(element => {
        let viewElement = element.getBoundingClientRect().top - window.innerHeight   20;
        if (viewElement < 0) {
            element.classList.add("view-element");
        } 
        else {
            element.classList.remove("view-element");
        }
    })
}

CodePudding user response:

The issue is that that the for ... in ... loop loops over all enumerable properties of an object. The NodeList that your querySelectorAll returns has numeric keys for each contained element BUT also contains the properties item, keys, values, entries, forEach, and length.

But these additional properties are not HTMLElements, hence, they don't have the method getBoundingClientRect.

See yourself:

const items = document.querySelectorAll('.item');

for (const item in items) {
  console.log('item: ', item);
}
<div ></div>
<div ></div>
<div ></div>
<div ></div>

Instead you want to use the for ... of ... loop.

const items = document.querySelectorAll('.item');

for (const item of items) {
  console.log('item: ', item);
}
<div ></div>
<div ></div>
<div ></div>
<div ></div>

  • Related