-2

For reusable code, I would like to make a JS function that takes an array of strings to turn into a top centered horizontal navbar and the id of where to put it. For this example we will make a few assumptions; namely that each string in the array represents the html filename, and the name we want for the button. Further, we will be using the w3.css 2.82.

So first the JS function:

function makeNavigation(navArray, navID) {
  var numNav = navArray.length;
  var spaceAllocated = (100 - 2) / numNav;
  var theID = document.getElementById(navID);
  for (var i = 0; i < numNav; i++) {
    theID.appendChild('<li style = "width:"'+spaceAllocated+'%><a  href="#'+navArray[i]+'.html">'+navArray[i]+'</a></li>');
  }

in the HTML, we have

<head>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
</head>

<div>
<ul id="test" class="w3-navbar w3-border w3-light-grey w3-center">

</ul>
</div>

<script>makeNavigation(["PageOne","PageTwo","PageThree"], "test")</script>

but this doesn't work. I have also just tried appendChild...

SumNeuron
  • 4,850
  • 5
  • 39
  • 107

1 Answers1

2

Here is a working example you can view on jsfiddle.net

I did notice that your for loop is missing a closing bracket in the example code you provided.

I did changed the .appendChild eventhandler to the .innerHTML += eventhandler

function makeNavigation(navArray, navID) {
  var numNav = navArray.length;
  var spaceAllocated = (100 - 2) / numNav;     //Spacing 2% for edges
  var theID = document.getElementById(navID);
  for (var i = 0; i < numNav; i++) {
    theID.innerHTML += '<li style = "width:'+spaceAllocated+'"%><a  href="#'+navArray[i]+'.html">'+navArray[i]+'</a></li>';
  } //missing closing bracket inserted here. 
}

Hope that helps.

SumNeuron
  • 4,850
  • 5
  • 39
  • 107
jameswassinger
  • 373
  • 3
  • 9
  • 1
    Thanks! Yeah missed it on my copy-paste. So how come innerHTML works and not appendChild? – SumNeuron Nov 02 '16 at 03:53
  • Here are a few explanations on that very topic: [“innerHTML += …” vs “appendChild(txtNode)”](http://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode), [The difference between 'innerHTML' and 'appendChild'](http://stackoverflow.com/questions/23338978/the-difference-between-innerhtml-and-appendchild), [What is the difference between appendChild, insertAdjacentHTML, and innerHTML](http://stackoverflow.com/questions/16126960/what-is-the-difference-between-appendchild-insertadjacenthtml-and-innerhtml). – jameswassinger Nov 02 '16 at 14:11