Home > front end >  Get id of each element when scroll to top in Angular
Get id of each element when scroll to top in Angular

Time:05-11

I want to get id of the section element when it reaches the top. Something similar has been done with jquery already but I want same with Angular. I tried in similar way but not getting success.

/*let content = document.getElementsByClassName('scrollable');
      this.listener = this.renderer2.listen('window', 'scroll', (e) => {
        
        let elementPos = el.getBoundingClientRect().top   window.pageYOffset;
    
        
        var el = Array.prototype.forEach.call(content, (el)=>{
            // console.log(el.id, el.getBoundingClientRect().bottom, parseInt(el.clientHeight))
            if(el.getBoundingClientRect().bottom >= parseInt(el.clientHeight)) {
              console.log({el})
            }
        })
        
        */
section {background: #ccc; height: 100vh;};
section:nth-child(odd) {background: red}
<section  id="scroll1"> Scroll1 </section>
<section  id="scroll2"> Scroll2 </section>
<section  id="scroll3"> Scroll3 </section>
<section  id="scroll4"> Scroll4 </section>
<section  id="scroll5"> Scroll5 </section>

CodePudding user response:

I am able to make it work on my own with little bit of experiment. Below code might help. Thanks

      let content = document.getElementsByClassName('scrollable');
      // let windowTop = window.scroll.offset()
      this.listener = this.renderer2.listen('window', 'scroll', (e) => {
        
        
          let scrollY = this.windowRef.nativeWindow.pageYOffset;
           let landingPage = Array.prototype.filter.call(content, (el)=>{
            //  console.log(el.id, scrollY, el.getBoundingClientRect().top)
              return scrollY > (el.getBoundingClientRect().top   window.pageYOffset - 80);
            })

            // console.log({landingPage})
            console.log(landingPage.at(-1).id)           
      
        });

CodePudding user response:

I made this stackblitz.

I stored offsetTop of sections and added a listener for scroll on window and checked if it reached the threshold.

  • Related