Skip to content

Instantly share code, notes, and snippets.

@Muirrum
Created March 19, 2019 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Muirrum/2c338afd4d92ea31396120d288b36c35 to your computer and use it in GitHub Desktop.
Save Muirrum/2c338afd4d92ea31396120d288b36c35 to your computer and use it in GitHub Desktop.
Javascript to create a templated navbar using bootstrap. Requires bootstrap and a <nav id="navbar"> to exist in the HTML file. Should be deferred.
// Define navbar variable
var nav = document.getElementById("navbar");
// Navbar setup
nav.setAttribute("class", "navbar navbar-expand-lg navbar-light bg-light");
// Create UL and container div
var contDiv = document.createElement("DIV");
contDiv.setAttribute("class", "collapse navbar-collapse");
contDiv.setAttribute("id", "navbarSupportedContent");
nav.appendChild(contDiv);
var navbar = document.createElement("UL");
navbar.setAttribute("class", "navbar-nav mr-auto");
contDiv.appendChild(navbar);
function addItem(name, href) {
var li = document.createElement("LI");
navbar.appendChild(li);
if (name.toUpperCase() == document.title.toUpperCase) {
li.setAttribute("class", "nav-item active");
} else {
li.setAttribute("class", "nav-item");
}
var link = document.createElement("A");
link.href = href;
link.setAttribute("class", "nav-link")
link.innerHTML = name;
li.appendChild(link);
}
// Format is addItem(LINK_TITLE, FILE_NAME)
addItem("Home", "index.html");
addItem("Test", "Test");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment