'How do I create a .js file that creates a navigation bar in html
Ok so, I am creating this site and I want every page to have a navigation bar, how do I make it so that instead of having to write the html for the navigation bar on every page, I just write in the .js file and add this javascript file to every page.
Btw, I'm not asking how to write a navigation bar in html, I've already done that.
Solution 1:[1]
For that, I would recommend that you use a UI library like React, which when paired with React Router will definately yeild you much cleaner code and a better development experience overall.
With that in mind, I know that there is a significant learning curve towards dominating new libs/frameworks, so one way you could do it using vanilla HTML, CSS and JS is by pasting your HTML code for the header into a variable and injecting it by using some DOM methods like .append or .insertAdjecentHTML on a selected element (div, header, body...).
Solution 2:[2]
If your site will contain mostly static content, then I suggest looking into a static site generator (SSG) like Jekyll, Hugo or Gatsby. When I started web development, I used Jekyll and it was very beginner friendly. You could then link from your navbar to your other pages normally.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TarcĂsio Surdi |
| Solution 2 | juicy-g |
