0

I have a mainmenu view:

    <div class="submenu">
    <ul>
        @foreach (var p in Model)
        {
            <li>
                <div class="manu_bg">
                    @Html.ActionLink(p.Name, "ListProductByGroupID", "Product", new { GroupID = p.GroupCategoryID, GroupName = p.Name }, null)
                </div>
                @{Html.RenderAction("ListCateByGroupID", "Category", new { GroupID = p.GroupCategoryID });
                }
            </li>
        }
    </ul>
</div>

and the View of submenu in mainview:

 @foreach (var i in Model)
    {
        <li>
                @Html.ActionLink(i.Name, "ListProductByCateID", "Product", new { CateID = i.CategoryID, CateName = i.Name }, new { id="link"})  
        </li>    
    }

and a little Javascript to add css class for active link:

 window.onload = ActiveLink;
function ActiveLink() {
    var link = document.getElementById("link");
        link.onclick = showActive;
}

function showActive() {
    var selectedlink = this.text;
    var link = document.getElementById("link");
        if (link.text == selectedlink) {
            link.className = " active";
        }
        else { link.className = ""; }


}

My javascript is not working?

1 Answer 1

0

Add an ID to that link so you can find it:

@Html.ActionLink(i.Name, "ListProductByCateID", "Product", new { CateID = i.CategoryID, CateName = i.Name }, new { id = "ListByCatLink" })</div>

Then select it by ID and add the class...

using pure Javascript:

var link = document.getElementById("ListByCatLink");
link.className = link.className + " active";

or jQuery if you're using that:

$("#ListByCatLink").addClass("active");
3
  • function ActiveLink() { var alllinks = document.getElementById("alinks"); for (var i = 0; i < alllinks.length; i++) { var currentlink = alllinks[i]; alert("In show link"); currentlink.onclick = showActive; } } It can't find or return 0 in my loops
    – Luffy
    Commented Jul 29, 2013 at 15:39
  • Why are you iterating through the return of getElementById? By definition, only one link will have that ID, so there will only be one, so you don't need to iterate... if you have multiple links you need to apply this to, use a class or a data attribute to mark them, and then find them by that. Commented Jul 29, 2013 at 15:55
  • Yes, i know. I want to add active class for my Sub Menu from Main menu View.
    – Luffy
    Commented Jul 29, 2013 at 16:12

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.