1

I need to find a way to use javascript to make multiple links for my left nav. I will have seperators dividing the links into categories. This is my current code.

links = new Array();
links[1]="<span class='asep' style='border-top: 0px; margin-top: 0px;'>Welcome</span>";
links[2]="<a href='#'>Home</a>";
links[3]="<span class='asep'>Body Jewelry</span>";
links[4]="<a href='#'>Circular Barbells</a>";
links[5]="<a href='#'>Belly Button</a>";
links[6]="<a href='#'>Curved Barbells</a>";
links[7]="<span class='asep'>User Controls</span>";
links[8]="<a href='#' onclick='window.print(); return false'>Print This Page</a>";


function writeLinks() {
 document.getElementById('nav1').innerHTML = links[1] + links[2] + links[3] + links[4] + links[5] + links[6] + links[7] + links[8];
 document.getElementById('featured').innerHTML = ' <b>Featured Product</b><br><a href="#"><img src="icon1.gif" border="0"><br>Product Title</a>';

}

    setTimeout(writeLinks, 0); // Fires the function on page load without stopping other loads

Is there an easier way to do this?

3 Answers 3

2

There are various aspects of your methods which can be made "easier":

links = new Array();

Can be better-written as links = [];. (almost) everything you'll come across in Javascript is already an object, so being verbose about it doesn't add clarity.

links[1]="first..."
links[2]="second...";

can be better-written using .push(), so that you don't need to specify each index, eg:

links.push("first");
links.push("second");

or, if you're doing it all at once, using an array-literal, eg:

links = [
    "first",
    "second"
];

less-nice, in my opinion, but also an option, could be a mixture of both, using .concat():

links = [
    "first",
    "second"
];

links = links.concat([
    "third",
    "fourth"
]);

It might make sense to group things together using an array of bare objects, too:

sections = [
    {
        heading: '<span class="asep">First section...</span>',
        links: [
            '<a href="#">First</a>',
            '<a href="#">Second</a>'
        ]
    },
    {
        heading: '<span class="asep">Second section...</span>',
        links: [
            '<a href="#">Third</a>',
            '<a href="#">Fourth</a>'
        ]
    },
];

function writeLinks(){
    var html = "";
    for( var i = 0; i < sections.length; i++ ){
        var section = sections[i];
        html += section.heading + section.links.join("");
    }
    document.getElementById('nav1').innerHTML = html;
}
setTimeout(writeLinks, 0);

Note also the use of .join("") to join all elements of an array together as strings.

Next, you've got a lot of duplication in your code. You could specify only the parts which are different, eg:

sections = [
    {
        heading: "First section...",
        links: [
            "First",
            "Second"
        ]
    },
    /* ...snip... */
];

function writeLinks(){
    var html = "";
    for( var i = 0; i < sections.length; i++ ){
        var section = sections[i];
        html += '<span class="asep">' + section.heading + "</span>";
        for( var j = 0; j < section.links.length; j++ ){
            html += '<a href="#">' + section.links[j] + "</a>";
        }
    }
    document.getElementById('nav1').innerHTML = html;
}
setTimeout(writeLinks, 0);

You could get rid of some of that raw HTML and simplify some of the loops, etc, by using a common library, such as jQuery or Prototype. This would also allow you to actually check that the document is ready for you to operate on it, rather than using that fragile setTimeout() hack. eg:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
/* ...snip... */
$(function(){
    var nav = $("<div />").attr("id", "nav1");
    $.each(sections, function(i,section){
        nav.append( $("<span />").addClass("asep").text(section.heading) );
        $.each(section.links, function(i,link){
            nav.append( $("<a />").attr("href", "#").text(link) );
        }
    }

    $("#nav1").replaceWith( nav );
});
</script>

All of those may be considered "easier" depending on your mood.

Sign up to request clarification or add additional context in comments.

Comments

1
var arr = [];
arr[0] = <span class='asep'>Body Jewelry</span>;
arr[1] = <span class='asep'>Do Something</span>;

function writeLinks(){
    document.getElementById("nav1").innerHTML = arr.join("");
}

Array.Join is faster than concat operation .

4 Comments

This doesn't fix the other larger issues with his approach. By suggesting your change you're encouraging him to stay with a flawed design.
I dont mind using arrays but when I try to print the contents of the array to innerHTML everything is seperated by commas.
@Tyler , We don't know what's his situation or design ?
@JesseToxik Array.join joins all elements in an array into one .
0

This might be a bit overkill, but you might want to look at a client side framework that supports models and templates, such as backbone.js. Then you could store all your links in a model which can easily be changed (and will automatically update the view for you through events), and you can also use underscore.js templates so you don't have to write any html as a string literal.

7 Comments

If there is a way to remove the commas from an array when you link an array to innerHTML I can use my code but my issue is I am going to have over 100 pages so I need something Dynamic :(
Storing your links in a model is exactly how you make them dynamic : ) And you can always iterate over the array and parse out the commas!
I guess you can tell im new to JS since my code is sucky lol how can i remove the commas?
Something like this might do the trick: function removeCommas() { for(var link in links) { link.replace(",", "") }}
Sorry, it's because the commas you are trying to remove are only generated AFTER you've called toString on the array... you could either use a template, or do the replace on the string representation of the array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.