简体   繁体   中英

javaScript changing parent menu item when child item is active

I'm pretty new to the javaScript and it would be very helpful for me if somebody could be so glad to give me some directions how to perform that. I'm creating website in Joomla 3 and I need to stylize the menu in a way that when a child menu item is active the parent item should change the background colour. I included the .js link into the head of the index.php file of my template. But I'm struggling second day with the desired script.

Here is my HTML:

<ul class="gf-menu l1">
    <li class="item128 parent">
        <a class="item" href"services">Services<span class="border-fixer"></span>::after</a>
        <div class="dropdown columns-1">
            <div class="column col1">
                <ul class="l2">
                    <li class ="item1"><a class="item" href="submenu-01">Submenu1</a></li>
                    <li class ="item2"><a class="item" href="submenu-02">Submenu2</a></li>
                    <li class ="item3"><a class="item" href="submenu-03">Submenu3</a></li>
                </ul>
            </div>
        </div>
    </li>
</ul>

And that's it my CSS for it:

.gf-menu .dropdown{
    border: 1px solid transparent; 
    border-radius:0; 
    background-color:#a9a9a9; 
    padding:10% 0; 
    width:100%;
    text-shadow:none;
    font-size:85%;
}
.gf-menu.l1 li.item1.active.last {background-color:#abcf39;}
.gf-menu.l1 li.item2.active.last {background-color:#f39512;}
.gf-menu.l1 li.item3.active.last {background-color:#f16e68;}

If you click on the <li> element and want to affect the parent you can use the .parent() method to target the parent element. The question is which one do you want to target. If it's the div which contains the <ul> you will have to access the parent of a parent. For example if the <li> has a class item as you stated in your question, you can do

$('.item').on('click', function(){
    var clickedLiElement = $(this);
    var parentHoldingUl = clickedLiElement.parent().parent();

    //now you can do whatever you want with both of them, for example
    clickedLiElement.addClass('active');
    parentHoldingUl.css('background-color', 'green');
});

Update based on comments:

A slightly shorter version, which does what you specified in the comments

$('.item').on('click', function(){
    $(this).css('background-color', '#5512F3');
    $(this).parent().parent().css('background-color', '#5512F3');
    $(this).siblings().css('background-color', '#AB99D5');
});

This should turn the clicked LI element and it's parent DIV dark blue and the clicked elemnent's siblings light blue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM