Selecting menu item using Javascript


Okay, I create a pure CSS menu that use UL/LI structure to maintain the child relationship. All was great with this menu except that when you are on any of menu item page it doesn’t highlight that menu item explicitly. If you consider this it is not a big deal. What you can do is simply, iterate through the Menu Items which are probably in LI A tags. Once you iterate, find the URL in A tag and match the Page URL with the Menu ITEM link. If they match change the Class of respective LI or A as your liking.

try {
    var path = window.location.pathname.replace("/User/", "");
    if (path == "" )
        path="Userhome.aspx";
    $("#mainemnu a").each(function () {

        if ($(this).attr("href").toLowerCase() == path.toLowerCase() ) {
            if ($(this).parent().hasClass("submenuitem")) { //it is sub menu
                $(this).parent().parent().parent().addClass("selectedmenu");
            } else {
                $(this).parent().addClass("selectedmenu");
            }
        }
    });
} catch (err) { }

That was a simple Jquery Driven Javascript function that I call in Document ready function of Jquery.

, , ,