1

Hi I'm trying to add some events to my page with a loop. this is my code

elements = $(".my-elements")
var i;
for (i = 0; i < elements.length; i++) {
    e = elements[i];
    document.addEventListener('scroll', event => {
        if( inViewport(e) ) {
            $(e).css({opacity: 1.0})
        }
    })
}

But after running the code, only the last event is applied, and previous events have no effect. what's the problem?

M-Jamiri
  • 127
  • 2
  • 9
  • 2
    Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – VLAZ Sep 15 '20 at 10:58

2 Answers2

1

Try this:

elements = $(".my-elements")
var i;
for (i = 0; i < elements.length; i++) {
    function() {
        var e = elements[i];
        document.addEventListener('scroll', event => {
            if( inViewport(e) ) {
                $(e).css({opacity: 1.0})
            }
        })
    }()
}
yunzen
  • 32,854
  • 11
  • 73
  • 106
0

i think the method is running synchronously, try to put it into an [async method][1], await for the function inside it and return a promise in each iteration. it will stop the execution of the async function until one iteration is completed like-

async function myEvent(){


  elements = $(".my-elements")
  var i;
    for (i = 0; i < elements.length; i++) {
      await function() {
      return new Promise((resolve,reject)=>{
          var e = elements[i];
           document.addEventListener('scroll', event => {
             if( inViewport(e) ) {
                  $(e).css({opacity: 1.0})
                  resolve();
              }else{
                  resolve();
              }
          })
    
     })
  }
  }
}

if there's an error in snippet you can correct it but take my point of going async. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

hemant kumar
  • 545
  • 6
  • 19