0

I am using ul and li to create a side menu. I have been trying to keep the selected menu highlighted but can't figure out what I am doing wrong. I tried using a class for top "ul" and handle its click as well as adding a class to each "li" and handle its click.

Some menu items have sub-menu.

This is what I have and what I tired:

<ul class="list-unstyled components mb-5">
    <li class="active component">
        <a href="\Home\">Dashboard</a>
    </li>
    <li class="component">
        <a href="#Sub1" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Item 1</a>
        <ul class="collapse list-unstyled" id="Sub1">
            <li>
                <a href="#">Sub-Menu 1-1</a>
            </li>
            <li>
                <a href="#">Sub-Menu 1-2</a>
            </li>
        </ul>
    </li>
    <li class="component">
        <a href="#Sub2" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Item 2</a>
        <ul class="collapse list-unstyled" id="Sub2">
            <li>
                <a href="#">Sub-Menu 2-1</a>
            </li>
            <li>
                <a href="#">Sub-Menu 2-2</a>
            </li>
        </ul>
    </li>
    <li class="component">
        <a href="/blah.aspx">Item 3</a>
    </li>
    <li class="component">
        <a href="/blah.aspx">Item 4</a>
    </li>
</ul>

JS/Jquery:

$(".component").on("click", "a", function(){  // Also tried with "ul" class of "components" instead of "component"
    //event.preventDefault();  // When I uncomment this, clicking the menu doesn't do anything
    $(this).parent().removeClass("active");
    $(this).addClass("active");
    //$(this).parent().addClass("active").siblings().removeClass("active");
});
NoBullMan
  • 2,032
  • 5
  • 40
  • 93
  • This might help you... https://stackoverflow.com/questions/33598738/set-and-get-value-using-session-storage-for-html-drop-down-with-jquery – dale landry Apr 01 '20 at 01:38

1 Answers1

0

Your class toggle is removing and then immediately adding the class back. Take a look into this for the toggle effect you need: https://api.jquery.com/toggleclass/

S Henry
  • 150
  • 5
  • Example doesn't seem to apply. I don't want sticky highlights like the example that allows multiple p elements be highlighted. Couldn't get it to work with my menu. – NoBullMan Apr 01 '20 at 03:57
  • Do not focus on an example. It is what you can do with the toggle on/off of your active class. Take the concept and apply it to your menu. – S Henry Apr 01 '20 at 14:09