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

React throwing error: Context value is undefined

Why is the Context value showing as undefined? The issue lies in src/Context.js: import React, { Component } from 'react'; const Context = React.createContext(); export class Provider extends Component { state = { a: 1, b: 2 }; render( ...

JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue? Below is the code I am currently usin ...

What is the best way to set the width of an element to 100% while accounting for padding

My dilemma involves an HTML input field. The input currently has padding: 5px 10px;, but I need it to occupy 100% of its parent div's width (which is fluid). If I try using width: 100%;, the input ends up being wider than intended due to the padding ...

What is the method for prompting a save as dialog in the browser in order to save JSON data stored in memory?

As the title suggests, I am looking for a way to store JSON data in memory. I want this action to be triggered by an onclick event on a DOM object. The goal is to save the data on the user's computer as if they were downloading a file. Saving it as t ...

Generate div elements corresponding to individual objects

Previously, I inquired about a similar issue but have not come across any solutions. I made updates to my code, which is now functioning well, however, I am facing a new dilemma. Here is the PHP code I am currently working with: class individual { pu ...

Using a key as an argument in the `map` function invocation

I keep getting a warning message stating that each child in the array does not have a unique key. const ITEMS = [ { "name": "apple", displayName: "Apple" "name": "orange", displayName: "Orange" }, { "name": "banana", di ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

Changing the input value in Nuxt / Vue 2 after it has been overridden

I'm working on a feature where the user's typed keys are converted to the last single upper-cased character (for example, 'a' becomes 'A', 'abc' becomes 'C'). Here is my current code snippet: <template& ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...

Having trouble loading IE with jQuery isotope

Encountering a common issue on an unfamiliar browser, many still face the challenge. Setting up an isotope grid on websites seems to function seamlessly across various browsers, except for when testing in Internet Explorer using . In this case, the layout ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

React - updating key prop does not trigger re-render of child component

I have implemented react-infinite-scroll to display a continuous feed of data. My goal is to refresh the data feed whenever the user makes any changes to their settings. To achieve this, I am utilizing a key prop for the InfiniteScroll component. The conc ...

Issue with scrolling to the bottom of collapsed sections in Bootstrap

I have a bootstrap collapse panel and I've added a toggle link at the bottom to allow users to expand and collapse the content with a click. The Issue My problem arises when the menu expands, causing it to scroll all the way to the bottom of the pag ...

Is there a way to link multiple GET requests and combine their results into an array in JavaScript/Node?

The current code is a bit messy, and I'm still unsure about the then method. What each 'get' call returns: An array with some, but not all, results. What I need: To pass two different URIs, concatenate the results of both, and then expor ...

Issue with Vue canvas $ref not being defined on resize causing error, but oddly still seems to function correctly

Within my application, there exists a tabbed interface. One of the tabs contains a canvas element that dynamically adjusts its size to fit the window whenever it is resized. The functionality works seamlessly at first, but upon switching tabs and returning ...

Issue with deep linking functionality on S3 storage service turning out to be

After successfully deploying my angular5 app to: http://myApp.s3domain.amazonaws.com The Angular router is automatically directing me to http://myApp.s3domain.amazonaws.com/home However, when I try to access a link with a unique parameter like so: http:/ ...

Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), bu ...

I require assistance on how to properly arrange images in a div so that they stack

I'm having an issue with arranging a series of images within a div where they stack on top of each other. The div has a CSS width of 450px, and the top image always matches this width. Subsequent images vary in size and need to be aligned flush right ...

Is it necessary to specify the server-side script within the "routes" directory?

I'm currently developing a NodeJS Express application and from what I gather, the communication between the server and client is achieved by incorporating an AJAX script in a JavaScript file (on the client-side) and implementing a listener function (f ...

The jQuery scrollTop function seems to be malfunctioning following an ajax request

My ajax call is functioning properly, but I am experiencing an issue with the scrollTo plugin from JQuery. It is not positioning the content where I want it to be located below. //This function reveals the email body when a list item is clicked. jQue ...