The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `sections` variable in the code somewhere, but I'm unsure where exactly I should do this.


            let sections = document.querySelectorAll("section");
            let navList = document.getElementById("navbar__list");
            const buildSecBtn = document.getElementById("newSection");
            const main = document.querySelector("main");

            let counter = 3;
            const buildSection = () => {
                counter++
                const newSec =  `<section id="section${counter}" data-nav="Section ${counter}">
                    <div class="landing__container">
                    <h2>Section ${counter}</h2>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
                    </div>
                    </section>`
                main.insertAdjacentHTML("beforeend", newSec);
            };

            const buildNav = () => {
                navList.innerHTML ="";
                sections = document.querySelectorAll("section");
                sections.forEach(section => { 
                    const navItem = `<li><a class="menu__link" data-nav="${section.id}" href="${section.id}">${section.dataset.nav}</a></li>`
                    navList.insertAdjacentHTML("beforeend",navItem)
                });
            };
            buildNav();

            let options = {
                threshold: .7
            };

            const sectionObserver = (entries, Observer) => {
                entries.forEach(entry => {
                    const activeLink = navList.querySelector(`[data-nav=${entry.target.id}]`)
                    if (entry.isIntersecting) {
                        entry.target.classList.add("your-active-class")
                        activeLink.classList.add("active__li")
                    } else {
                        entry.target.classList.remove("your-active-class")
                        activeLink.classList.remove("active__li")
                    };
                });
            };

            let Observer = new IntersectionObserver(sectionObserver, options);

            sections.forEach(section => {
                Observer.observe(section)
            });

            buildSecBtn.addEventListener("click", () => {
                sections = document.querySelector("section")
                buildSection();
                buildNav();
                sectionObserver();
            })
        

            body {
                background: rgb(136,203,171);  
                /* Additional CSS properties */
            }
            /* Copy and modify remaining CSS here */

        

            <!DOCTYPE >
            <html lang="en">
            <head>
              <!-- Metadata -->
            </head>
            <body>
              <header class="page__header">

              </header>
              <main>

              </main>
              <footer class="page__footer">
                
              </footer>
            </body>
            </html>
        

Answer №1

There are a couple of areas in your code that need some attention:

  1. Avoid calling the sectionObserver function inside the build section click event listener. This function is meant to be a callback for internal use by the intersection observer object.

  2. Make sure to include a reference to the intersection object when invoking the buildSection function, and then specify the element you want to observe within it.

Implementing these changes should help resolve the issue you're facing.

Check out the relevant snippets provided below.

buildSecBtn.addEventListener("click", () => {
    sections = document.querySelectorAll("section")
    buildSection(Observer);
    buildNav();
    //sectionObserver();
})

const buildSection = (_observer) => {
    ...
    main.insertAdjacentHTML("beforeend", newSec);
    const target = document.querySelector(`#section${counter}`);
    _observer.observe(target)

};

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

My backend axios post request is not returning any data to my external API. What could be the issue?

I've encountered an issue where I'm attempting to transmit data from my client-side using an ajax call to my backend axios post request, which is responsible for posting data to an external API URL. Despite receiving a 200 status code, none of th ...

Guide on how to selectively add middleware such as multer to a fresh express router

For a previous project, I set up a router and utilized multer for handling file uploads. I was able to apply the multer middleware selectively on specific routes as shown below: var router = express.Router(); var multer = require('multer'); var ...

Disappearing markers issue in Openlayers when zooming

I am trying to ensure that markers on the map do not get erased when zooming in or out. Here is my script: JS $(document).ready(function() { //initialization var map; var markerPosition; // Marker position var options = { restrictedE ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Exploring the integration of d3 in an Express application - encountering an error: document is not recognized

I am facing a challenge in my expressjs application where I need to dynamically render vertices in a graph using d3. However, the code execution order seems to be causing issues for me. When attempting to use the d3.select function, I encounter the followi ...

Having trouble with my router in the express app - the .find and .findByID methods are not working properly. Also,

In my current setup with NextJS/MERN stack, I am using the server.js file in NextJS to import API routes and make API calls. The routes seem to be functioning properly as there is activity when calling them from Postman or the browser. However, it appears ...

Maintain the image's aspect ratio by setting the width equal to the height when the height is

I am uncertain if achieving this purely with CSS is possible, but it would be ideal. I currently have an image: <img src="#" class="article-thumb"> CSS: .article-thumb { height: 55%; } Is there a way to set the width equal to the height? My g ...

Adjust the class based on the number of li elements

When there are more than two (li) tags, the ul tag should have the class "col_3"; otherwise it should have the class "col_2" For instance: If there are two columns <div class="container"> <ul class="col_2"> <li>One</li> ...

Styling the Menu Item with CSS

A graphic designer provided me with these elements to incorporate into the HTML design. Everything was going smoothly until I encountered the faint, uneven borders on the LI tags, especially when dealing with a list containing only five items. If anyone ...

Learn how to assign unique IDs to each input radio field in a Grails GSP radiogroup

Is there a way to assign a unique id for each input attribute in a GSP Grails application? <g:radioGroup id="x"> ${it.label} ${it.radio} </g:radioGroup> It seems that using id="x" is not functioning as expected. ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...

Display information from a selected card on a separate page upon clicking

I am currently working with a JSON file to display cards on a webpage. The code is sourced from a file named paintings.js and the cards are rendering correctly. However, when I click on a card, it redirects me to a blank paintingInfo.js page. I'm wond ...

Generate a Year attribute value using the information from the year field in a JSON document

Currently, I am exploring the functionalities showcased in this example: I am interested in adapting the following code snippet to work with my JSON file, which lacks a specific date data type field but includes a 'Year' value: // Transform Yea ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present ...

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

Issue with ASP.NET Base64 image source rendering incorrectly

After retrieving a Base64 string from Azure active directory using a Lambda function, which represents a user's profile picture, I am facing issues displaying it on an ASP.NET page. Below is the code snippet in ASP.NET (The referenced HTML object is ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...