0

I'm using Github Pages to make a website for myself, and I recently came around to adding a navbar to it. So, after searching the web for some help for what felt like an eternity, I finally found a solution for putting it in any html page in a stack overflow question, and the actual html for the navbar from w3schools.

The solution was to use a js file to fetch the contents from navbar.html, and put it in the file where the script was being called using the <script> tag. Or at least that's what I understood - I'm relatively new to javascript.

fetch('navbar.html')
  .then(res => res.text())
  .then(text => {
    let oldelem = document.querySelector("script#navbarJS");
    let newelem = document.createElement("div");
    newelem.innerHTML = text;
    oldelem.parentNode.replaceChild(newelem, oldelem);
  })
body
{
    background-color: rgb(var(--background));
    color: rgb(var(--foreground));
    font-family: "Raleway", sans-serif;
}

.mono
{
    font-family: "SF Mono", "Consolas", monospace;
}
<style>
  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
  }
  
  li {
    float: left;
  }
  
  li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
  }
  
  li a:hover {
    background-color: #111;
  }
</style>

<ul id="navbar">
  <li><a class="active" href="about:blank">Home</a></li>
  <li><a href="about:blank">Button 1</a></li>
  <li><a href="about:blank">Button 2</a></li>
  <li><a href="about:blank">Button 3</a></li>
  <li style="float:right">
    <div class="mono">v0.1.0</div>
  </li>
</ul>

But I soon encountered a problem - trying to put <script id="navbarJS" src="navbar.js"></script> into an html file in a different folder than navbar.js put a 404 error at the top of the page, with the actual content below it. Weird.
But it wasn't long before I realized that I could simply change it to src="./navbar.js" to get rid of the 404 error, and I assumed that means that navbar.js has actually been executed.
And sure enough, viewing the page's source shows that the script had inserted nothing.

However, the navbar is still not visible - so I'm guessing this has something to do with navbar.js itself. Here's the code:

fetch('navbar.html')
  .then(res => res.text())
  .then(text => {
    let oldelem = document.querySelector("script#navbarJS");
    let newelem = document.createElement("div");
    newelem.innerHTML = text;
    oldelem.parentNode.replaceChild(newelem, oldelem);
  })

This is probably just a syntax error that I, a newbie to js, am completely missing.
Does anyone know what exactly I'm missing, though?

just-a-hriday
  • 148
  • 1
  • 13

0 Answers0