Mindless
Mindless

Reputation: 2357

Highlight parent menu item using javascript

When i click on parent menu item, it highlights all child menu items in the dropdown menu, how do i fix that.

javascript:

$(function () {
    var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
    $('[href$="' + url + '"]').parents("li").addClass("current_menu_item");
});

css:

#menu ul .current_menu_item a /* highlight current menu */
{
    color: Yellow;
}

html:

<div id="menu">
    <ul>
        <li><a href="/Services.aspx" class="top_parent" title="Our services">Services</a>
            <ul>
                <li><a href="/Design.aspx">Design</a></li>
                <li><a href="/Construction.aspx">Construction</a></li>
                <li><a href="/Refurbishment.aspx">Refurbishment</a></li>
            </ul>
        </li>
        <li><a href="/Experience.aspx" title="Our experience">Experience</a></li>
        <li><a href="/Ourwork.aspx" title="Our previous work">Our Work</a></li>
        <li><a href="/Contact.aspx" title="Contact us">Contact</a></li>
        <li><a href="/About.aspx" title="About us">About</a></li>
    </ul>
</div>

When i click on a dropdown menu item, it highlights its parent menu item and all my dropdown menu items, like so(yellow is highlight, blue is hover):

enter image description here

How do i use javascript to remove highlight on dropdown menu items, or highlight the parent menu and selected dropdown menu item.

Upvotes: 2

Views: 962

Answers (2)

Aristos
Aristos

Reputation: 66641

This line .parents("li") is locate all parents li, but you need only the first one.

So change it with closest() and make it as:

$(function () {
    var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
    $('[href$="' + url + '"]').closest("li").addClass("current_menu_item");
});

And online test with closest: http://jsfiddle.net/56fqd/
with parents : http://jsfiddle.net/56fqd/1/

Upvotes: 0

Natalie Hedstr&#246;m
Natalie Hedstr&#246;m

Reputation: 2621

You can use the child selector > to only target the a elements that are immediate children of .current_menu_item

change #menu ul .current_menu_item a to #menu ul .current_menu_item > a

Upvotes: 3

Related Questions