Determine the id of every element when scrolling to the top in an Angular application

I am searching for a way to retrieve the id of the section element when it reaches the top. A similar task has been accomplished using jQuery on Stack Overflow, but I am looking to achieve the same with Angular. I have tried a similar approach but without any 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 class="scrollable" id="scroll1"> Scroll1 </section>
<section class="scrollable" id="scroll2"> Scroll2 </section>
<section class="scrollable" id="scroll3"> Scroll3 </section>
<section class="scrollable" id="scroll4"> Scroll4 </section>
<section class="scrollable" id="scroll5"> Scroll5 </section>

Answer №1

I managed to get it working through my own experimenting. Here is the code snippet that might be useful. Thank you

      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)           
      
        });

.....edited.....

I made some corrections to @Mahdi Zarei's code and saw some progress. Check out a demo on StackBlitz

import { AfterViewInit, Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  constructor() {}

  ngAfterViewInit() {
    // @ts-ignore
    const sections : any = Array.from(
      document.getElementsByClassName('scrollable') as HTMLCollectionOf<HTMLElement>
    ).map((section) => [section.id, section.offsetTop]);
    window.addEventListener('scroll', function (ev) {
      let foundIndex = 0;
      sections.forEach((sec, index) => {
        if (document.scrollingElement.scrollTop >= sec[1]) {
          foundIndex = index;
        }
      });
      document.getElementById('el').innerText = sections[foundIndex][0];
    });
  }
}


Answer №2

Check out this unique stackblitz that I created.

By storing the offsetTop of sections and setting up a scroll listener on the window, I was able to determine when it reached the specified threshold.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do the jQuery fadeIn() and animation() functions operate in a non-blocking manner?

When my page loads, it initiates multiple ajax queries using $('document').ready(). I want to incorporate fadeIn() or animation() to briefly display some information after the first ajax call is received. Would the subsequent js/ajax calls be he ...

Creating a responsive body background design

For quite some time now, I've been grappling with this issue and despite my best efforts, I haven't been able to crack it. Essentially, I have a background image set for the body tag. However, whenever I add text on top of the background, the ima ...

What is the best way to sequentially increment column numbers in Javascript?

Implement two buttons: one to add a row at the top below the header row with data, and another to add a row at the bottom with data. The columns will adjust automatically. <body> <table id="tbl"> <tr> <th>S. ...

Is there a way to display error messages next to the input field in Bootstrap 4?

https://i.sstatic.net/0B1rM.png I am interested in changing the placement of error messages to the right side instead of the bottom of the "By" input element. Here is the code snippet: <div class="row "> <div class="c ...

Expanding the content to fit the text alignment

I have implemented text justification on a block of content. Here is a link to view the text: Click here Upon closer inspection, you may notice that within the text block, some words are stretched out to fill the space but this causes an abnormal spacing ...

Node Express combined Frontend and Backend routes under one URL path

I am currently developing an URL shortener using NodeJS and Express for the Backend, along with Angular for the Frontend, all deployed within a single docker container. The key feature of redirecting from short URLs to long URLs needs to be managed at the ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'. In my express app setup, I have the following configuration: // Entry Point app.use("/", express.static(resolve(__di ...

Utilize Bootstrap to align fields in the center

I'm new to using bootstrap and I could really use some help centering these text boxes and button. Any additional suggestions for improving the code would be greatly appreciated. My code is based on this template: https://github.com/BlackrockDigital/ ...

What is the method by which jQuery achieves synchronous behavior in its $.ajax function?

I previously asked a similar question on Stack Overflow, but I wanted to approach it from a different angle to get more feedback. So far, I haven't found a solution that works for me. I am trying to make XCode execute a JavaScript command and receive ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Exploring how to display JSON objects containing spaces in an HTML table

Sorry if this question has been asked already, but I can't find the answer. I'm brand new to html/java/django and struggling with a seemingly simple issue. I am developing a web application that retrieves json data from firebase using python/pyre ...

Having trouble getting Plaid Link to open when using a combination of Javascript and Python

Whenever I try to call the plaid link handler, it spins for a while and then disappears. I am facing an issue where the link dialog box does not show completely, preventing me from accessing the access token. My setup involves using Flask for the Python se ...

Is there a way to duplicate a GLTF model that has been imported into the Autodesk Viewer?

I encountered an issue while trying to dynamically clone a loaded GLB model and allow the user to position it in the scene. Despite using the model.clone() method, the cloned model ends up appearing at the same position as the original, causing changes in ...

The parameter 'Barable' cannot be assigned to the parameter 'T' as they are not compatible

Could anyone help me understand why this code isn't functioning as intended: class Fooable { foo: string; } class Barable extends Fooable { bar: boolean; } function simplifiedExample<T extends Fooable>(): Array<T> { let list ...

Troubleshooting Issue with Post/Get Request in AJAX and Flask Framework

My current project involves building a YouTube scraper webpage purely for educational purposes. I have created a web page with a text box to enter search queries and a search button. When the button is clicked, an Ajax post request is sent with the text bo ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

ReactJS error: Unrecognized property <problem>

Issue: I am facing a problem where the 'completed' property set to a boolean in my to-do list is not getting checked when using toDoData.map (item =>). Within my ToDoData.js file, I have defined a property called "completed" with true or fals ...