Search code examples
javascripthtmlcssloopsmultiple-instances

Javascript run function inside multiple divs with the same class but different variables


I'm trying to run the same function inside multiple container divs with the same class on scroll.

I need to calculate different values for each container and use them on that specific function. The thing is that I need to use classes and I don't know how many containers each page is going to have.

This is my html:

   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>
    

   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>

    
   <div class="div-container container">
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
      <div class="div-inside"></div>
      <div class="div-inside-2"></div>
   </div>

And this is what I'm trying

var p1 = document.getElementsByClassName('div-inside')

    function moveDivinside() {

      const divcont = document.querySelectorAll('.div-container')
      divcont.forEach(element => {

        let marginWintop = element.getBoundingClientRect().top; 
        let winHeight = window.innerHeight;
        let difference = winHeight - (winHeight - marginWintop);

                let p1n;
                for (p1n = 0; p1n < p1.length; p1n++) {
                    p1[p1n].style.top = difference * .09 + 'px';
                }
        });
    }
    window.addEventListener('scroll', function () {
            requestAnimationFrame(moveDivinside)
    }, false) 

It seems it's only getting data from last container.


Solution

  • You need to slightly change your code:

    // this line needs to go: 
    // var p1 = document.getElementsByClassName('div-inside')
    function moveDivinside() {
      const divcont = document.querySelectorAll('.div-container');
      divcont.forEach(element => {
        // you need to select the elements inside the current element
        var p1 = element.getElementsByClassName('div-inside');
    
        let marginWinTop = element.getBoundingClientRect().top;
        let winHeight = window.innerHeight;
        let difference = winHeight - (winHeight - marginWinTop);
    
        let p1n;
        for (p1n = 0; p1n < p1.length; p1n++) {
          p1[p1n].style.top = difference * 0.09 + 'px';
        }
      });
    }