Manipulating an unordered list of links using jQuery

WARNING: This code was copied/pasted in from my old blog and there was some problem with the code example. It currently won’t work

The online fantasy football hosting site I use has lots of capability to modify layout and CSS, but some things are hard-coded and are only able to be manipulated using the DOM. They offer capabilities similar to that of MySpace. By that I mean you can add CSS and scripting via “Home Page Messages” so you can enhance and manipulate the layout of your site.

Someone asked how to manipulate navigation using javascript. I thought I’d tackle the task and get some more jQuery practice while I was at it. Here is what I came up with:

$(document).ready(function() {
    removeMenuLink($hm, HM_MENU, "Message Board");
    addMenuLink($hm, HM_MENU, "Test", "#/Test/Link", 1);
    addMenuLink($vm, VM_LEAGUE, "Example", "http://www.example.com", -1);
    removeMenuLink($vm, VM_LEAGUE, "Accounting");
});

var $hm = "#hsubmenu ul";
var $vm = "#vsubmenu ul li ul";
var HM_MENU = 0;
var VM_FRANCHISE = 0;
var VM_LEAGUE = 1;
var VM_STANDINGS = 2;
var VM_PLAYERS = 3;
var VM_HELP = 4;

function addMenuLink(menu, section, name, url, idx) {
    var $ul = $(menu);
    var link = "" + name + "";
    if (idx > -1 && idx < $ul.find("li").length) {
        $($($ul[section]).find("li")[idx - 1]).before(link);
    } else {
        $($ul[section]).append(link);
    }
}

function removeMenuLink(menu, section, name) {
    var $ul = $(menu);
    $($ul[section]).find("li").each(function() {
        var txt = $(this).find("a").text();
        if (name == txt) {
            $(this).remove();
        }
    });
}

As you can see, there are two functions: addMenuLink and removeMenuLink. There were requests for both, so I took a shot at each. Since many of the users have no clue how to use javascript and/or CSS, I tried to make the example as simple as possible. I created variables to hold the jQuery selectors for each menu (the site users asked to modify a horizontal and/or vertical sub-menu on the site). I also defined “constants” for that define the index of sections of the menus: the horizontal menu is a single section, and the vertical is broken up in to 5 sections. I had to define the single horizontal section to enable code reuse.

Each of the functions is called with a reference to the menu and the section. The addMenuLink function also takes in the link text, URL, and the list position to place the new link. The removeMenuLink simply takes an additional string of the menu link text to remove. I wanted to make it more simple than asking for an index of the item to remove. As I said, these users don’t necessarily know what they are doing beyond the brief instructions and help given to them on the site forums.

Anyway, I don’t know how useful this is, but it may come in handy for someone out there on the tubes. Enjoy!