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

Generate a JSON object specifically for the modified input fields upon submitting the form

Is there a way to generate a JSON object only with the input fields that have been modified before submitting the form? How can I capture and store each changed value in the form as JSON data? $(document).ready(function() { $('#save').clic ...

leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance. The problem at hand is related to a workout ...

Why isn't the button border displaying the color I assigned to it?

After setting a border color to my button, it's not displaying the color when I click on it. Instead, it's showing a different color. How can I resolve this issue? I need some assistance with setting the background of my button to match the imag ...

What causes certain CSS properties to scroll while others remain fixed?

I am experiencing a strange issue with my table. I am utilizing the tableHeadFixer jQuery plugin to create a fixed header with a scrollable table body. In my CSS, I have a class called table which is defined as follows: .table thead { color: blue; ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

Saving HTML elements within an XML file

I am dealing with a String that has an html format containing various html tags. My goal is to enclose this string within xml tags while preserving the html tags, for example: public class XMLfunctions { public final static Document XMLfromString(Str ...

Encountered issue #98123: Failed to generate development JavaScript bundle during `gatsby develop` using Webpack

To set up a new Gatsby starter blog, I executed the following commands: gatsby new blog https://github.com/alxshelepenok/gatsby-starter-lumen cd blog gatsby develop However, while running gatsby develop, I encountered numerous errors labeled as ERROR # ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

changing the RadioButtonList to preselect a default value

On a page, I have a pre-existing RadioButtonList where I want to make the second button checked by default instead of the first one. Since I am unable to edit the original control directly, it seems like I might need to achieve this using javascript on th ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

The alignment of CSS boxes at the top is off

My challenge is to stack 3 containers horizontally, but they have different heights and the smaller ones end up at the bottom. How can I resolve this issue? This is the code snippet I am currently using for the boxes: .brand{ border: 1px solid black; bor ...

Ensure the date is displayed in the format of dd-mm-yyyy when using the input type=date

Here is the code I am currently using : <input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" max=<?php echo ...

Transferring information to a subordinate view

I'm working on developing a single-page application and need to transfer data to a child view. After fetching the API using Axios, I am able to successfully log the data in the console. However, when trying to display the data in the child view, I en ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The ...