0
<script type = "text/javascript"> //Add spaces between menu links //Placement: Global Header //Coded by Game var spaces = "2"; //Edit number of spaces between menu links (1,2 or 3) var a = document.getElementsByTagName("a"); for (i = 0; i < a.length; i++) { if (a[i].parentNode.parentNode.className == "menubg" && a[i].innerHTML.match(/Home|new topics|help|search|members|calendar|admin|profile|logout|register|login/i)) { if (spaces == "1") { a[i].innerHTML += "&nbsp;"; } if (spaces == "2") { a[i].innerHTML += "&nbsp;&nbsp;"; } if (spaces == "3") { a[i].innerHTML += "&nbsp;&nbsp;&nbsp;"; } } } </script> 

The code above is meant to let the useer add spaces between their menu items. It works fine. But how do I make it to where they can add as many spaces as they would like, instead of limiting them to 3? Maybe somehow they would add their number in the var 'spaces' and the code would multiply &nbsp by that numvber?

4 Answers 4

4

Just use a loop:

var spaces = 2; [..] for(var i = 0; i < spaces; ++ i) a[i].innerHTML += "&nbsp"; 
Sign up to request clarification or add additional context in comments.

Comments

1

I would generate the string in a separate method, like:

function getSpaces(count) { var spaces = ""; for(var i = 0; i < count; i++) { spaces += "&nbsp"; } return spaces; } 

and then

a[i].innerHTML = getSpaces(2); //etc 

This way you set innerHTML and access the array only one time, and also don't have repeated code.

Comments

0

Avoid innerHTML if you can, since it deletes and recreates the entire content of the element. Prefer appendChild and createTextNode instead. For instance:

a[i].appendChild(document.createTextNode(new Array(spaces + 1).join("\u00A0"))); 

Comments

0

Why don't you just create a loop inside your if clause that adds an &nbsp; every time you go through the loop?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.