While it includes a new section, it fails to refresh the navbar

Upon clicking the button to add a new section, the section gets added successfully. However, the navbar does not get updated as expected. It should dynamically update the navbar to display both the existing sections and the new section added using JavaScript. I am unable to identify what is causing this issue. If you have a solution, please feel free to share.

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

/**
 * End Global Variables
 * Start Helper Functions
 * 
*/
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. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lect...
    main.insertAdjacentHTML("beforeend", newSec);

};



const buildNav = () => {
    navList.innerHTML ="";
    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();

buildSecBtn.addEventListener("click", () => {
    buildSection();
    buildNav();
})
body {
    background: rgb(136,203,171);
    background: linear-gradient(0deg, rgba(136,203,171,1) 0%, rgba(0,13,60,1) 100%);
    margin: 0;
    font-family: 'Merriweather', serif;
    color: #fff;
}


/* Typeography General*/
h1 {
    font-family: 'Fira Sans', sans-serif;
    font-size: 3em;
    margin: 2em 1rem;
}

@media only screen and (min-width: 35em){
    h1 {
        font-size: 7em;
        margin: 2em 4rem 1em;
    }
}

h2 {
    border-bottom: 1px solid #cc1;
    font-family: 'Oxygen', Sans-Serif;
    font-size: 3em;
    color: #fff;
}

p {
    line-height: 1.6em;
    color: #eee;
}

/* ---- Layout Rules ---- */
main {
    margin: 10vh 1em 10vh;
}

.main-hero {
    min-height: 40vh;
    padding-top: 3em;
}

section {
    position: relative;
    min-height: 80vh;
}



.navbar__menu ul {
    padding-left: 0;
    margin: 0;
    text-align: right;
}

.navbar__menu li {
    display: inline-block;
}

.navbar__menu .menu__link {
    display: block;
    padding: 1em;
    font-weight: bold;
    text-decoration: none;
    color: #000;
}

.navbar__menu .menu__link:hover {
    background: #333;
    color: #fff;
    transition: ease 0.3s all;
}

/* Header Styles */
.page__header {
    background: #fff;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 5;
}

#newSection {
    background-color: black;
    position: sticky;
    width: 5rem;
    color: wheat;
}


.page__footer {
    background: #000;
    padding: 3em;
    color: #fff;
}

.page__footer p{
    color: #fff;
}


/* ---- Theme Rules ---- */
/* Landing Container Styles */
.landing__container {
    padding: 1em;
    text-align: left;
}

@media only screen and (min-width: 35em){
    .landing__container {
        max-width: 50em;
        padding: 4em;
    }
}

section:nth-of-type(even) .landing__container {
    margin-right: 0;
    ...
</html>

Answer №1

It seems like the issue lies within your section variable in the buildNav function. Make sure to re-search for sections to update the section variable:


const buildNav = () => {
    navList.innerHTML = "";
    sections = document.querySelectorAll("section"); /* Perform a new search for all sections */
    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)
    })
}

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

tips for extracting information from a PHP array

I've been attempting to analyze the following PHP array, but I'm encountering an issue where I'm not getting the expected output. Array: Array ( [0] => Array ( [countNos] => 2 [question_id] =&g ...

Tree Grid in jqGrid with Offline Data

Accessing the jqGrid documentation for tree grid, I discovered the following information: "At present, jqGrid can only interact with data that is returned from a server. However, there are some tips and resources available that explain how to work w ...

Remove elements by specific value in JQuery, not by index position

I am looking to remove certain elements from the instances list, specifically those set to "three" or "five". The index of these elements can vary: { "address": "localhost", "name&lqt;"local"", "vars": { "instances" ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

The @mouse-down event in Vue does not seem to be firing

I'm new to web development and I'm having some issues with Vue. I learned from a tutorial that I can use @click when a button is pressed, and it works fine. Now I want to create a simple mechanism to detect when the mouse is clicked and released ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Unable to retrieve array data using the post method in PHP and Angular.js

I am encountering a problem with my form submission using Angular.js and PHP. Despite sending an array of data to the server side using the $http service, I am not receiving any values on the server side. Below is an explanation of my code. var supplierDa ...

Using Google Maps to Cluster Markers on Your Website

I need to display numerous markers on a map for my website. My inquiry is whether the google maps api for javascript still supports clustering for websites? I attempted using marker cluster and it seems like it's not functioning properly. If so, can ...

Utilizing jQuery taggd to add annotations to images

I am currently utilizing the taggd Plugin to develop an application that creates a tag whenever any part of the body is clicked. I have successfully implemented most aspects of it, but I am facing an issue with the coordinates. The tags are sometimes creat ...

Sidebar-driven top navigation menu

I am currently developing a Single Page Application using VueJS along with vuerouter. In my App.vue file, the structure is as follows: <template> <div id="app"> <header><topbar></topbar></header> <div cl ...

Vue: add a CSS class to products when they are in the shopping cart

As I delve into creating a shopping cart using laravel + vue, I am encountering a major obstacle related to vue's functionality. Within my cart component, the goal is to allow users to effortlessly add or remove products by simply clicking. When a pr ...

My Jquery "animate" is only triggered once instead of on each function call. What could be causing this issue?

I have set my navigation to dock at a specific document height on the top of the viewport, and when it docks, it should display a dropdown animation. $(document).scroll(function(){ var x = $(window).scrollTop(); if(x>=700){ $("header ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

Ways to conceal all components except for specific ones within a container using JQuery

My HTML structure is as follows: <div class="fieldset-wrapper"> <div data-index="one">...</div> <div data-index="two">...</div> <div data-index="three">...</div> < ...

Issue with unbinding events in Angular directive persists despite efforts to completely unbind

Our directive features a popup that loads a template with a directive to capture all clicks in the document. When a click is detected, it sends an event to close the popup and unbinds the event on the $document. This directive effectively captures docume ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

Employing API Integration with Node.js and AngularJS

Currently in the process of developing a language translating messaging application using Node and Angular. I have decided to utilize the Yandex API since Google Translate is not free. You can find more information about the API at www.yandex.com I am unc ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

When an image is loaded, use Jquery to automatically open a new tab, instead of

I need to implement a function where, on loading an image on a page, a new tab opens and starts downloading a file from a specific URL while keeping the original page open. This task is part of a WordPress site with a jQuery section in the backend. I' ...