0

I want to make two tables to identify the position of each image before an animation. I tried several solutions I think the most logical would be a .push() but it doesn't work. Here is a code snippet:

const img = document.querySelectorAll('.myClass img')
let fromRight = []
let fromLeft = []
for (let i = 0; i < img.length; i++) {
  document.addEventListener('load', ()=>{
    if (img[i].getBoundingClientRect().x < (window.scrollY/2)) {
      fromLeft.push(i)
    } 
    else if (img[i].getBoundingClientRect().x > (window.scrollY/2)) {
      fromRight.push(i)
    }
  })
  console.log('left :', fromLeft);
  console.log('right :', fromRight);
}

I also tried:

Array.prototype.push.apply(fromLeft, i)

And :

fromLeft.concat(i)

Please I need help!

5
  • You might want to clone the array and push into the new one instead. Pushing inside the loop changes the length so the loop probably doesn't loop how you would expect. Commented Mar 1, 2022 at 15:19
  • 1
    @youdateme But they are not pushing into the array they are looping on. Besides, the push is happening in a callback, so is most likely not occurring until a later time. Commented Mar 1, 2022 at 15:22
  • document.addEventListener('load', ()=>{ Should that be img[i].addEventListener('load', ()=>{ ?? Commented Mar 1, 2022 at 15:22
  • You're adding a new independent "load" listener to the document for each image. Either that whole block should be wrapped in a single listener, or remove the listeners entirely, but definitely don't add a document listener for each image. Commented Mar 1, 2022 at 15:54
  • @James I also tried Commented Mar 1, 2022 at 15:57

1 Answer 1

1

Try wrapping the whole code inside a single listener

document.addEventListener('load', ()=>{
  const img = document.querySelectorAll('.myClass img')
  let fromRight = []
  let fromLeft = []
  for (let i = 0; i < img.length; i++) {
    if (img[i].getBoundingClientRect().x < (window.scrollY/2)) {
      fromLeft.push(i)
    } 
    else if (img[i].getBoundingClientRect().x > (window.scrollY/2)) {
      fromRight.push(i)
    }
  }
  console.log('left :', fromLeft);
  console.log('right :', fromRight);
})

Sign up to request clarification or add additional context in comments.

6 Comments

thanks but is not working, the response in the concole is : main.js:13 Uncaught ReferenceError: fromLeft is not defined
Doesn't make sense since it's defined in that very function. Check for typos.
yes I have no more error message indeed thank you
the only problem is that now only the last array gets filled with all the values
Perhaps you meant window.innerWidth / 2 instead of window.scrollY / 2? Not really sure.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.