Angular Angular - 3 months ago 11
CSS Question

how to highlight currently clicked h3 and li elements jquery

I have a accordian-style nav here. So every time an H3 is clicked, the list items drop down.

1.I want to color the H3 green if it's clicked, so users know what's currently clicked.

2.I also want to color whatever item/dog is clicked ( the < a > elements).
So the currently clicked Heading and subheading should both be highlighted.

<div id="accordian">
<ul class="sidebar-nav" id=menu>
<li class="active">
<h3>ITEMS</h3>
<ul>
<li><a href='#item1"> item1</a></li>
<li><a href='#item2"> item2</a></li>
<li><a href='#item3"> item3</a></li>

</ul>
</li>

<li>
<h3>dogs</h3>
<ul>
<li><a href='#dog1"> dog1</a></li>
<li><a href='#dog2"> dog2</a></li>
<li><a href='#dog3"> dog3</a></li>

</ul>
</li>

</ul>
</div>


THis is what I tried so far for 1, it doesn't work. Also, not sure how to do 2.



.sidebar-nav li.active{
color:green;

}





$('ul.sidebar-nav li h3').on('click', function(){
$('ul.sidebar-nav li').removeClass('active');
$(this).addClass('active');

});

Answer

You can do something like this:

$('ul.sidebar-nav li h3').on('click', function(){
    $("ul.sidebar-nav li ul li, ul.sidebar-nav li h3").removeClass("active");
    $(this).addClass("active");
});

$('ul.sidebar-nav li ul li').on('click', function(){
    if($(this).parents("li").find("h3").hasClass("active")){
        $(this).addClass("active");
    }
});
.active{
  color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordian">
        <ul class="sidebar-nav" id=menu>
            <li>
                <h3>ITEMS</h3>
                <ul>
                    <li><a href="#item1"> item1</a></li>
                    <li><a href="#item2"> item2</a></li>
                    <li><a href="#item3"> item3</a></li>

                </ul>
            </li>

             <li>
                 <h3>dogs</h3>
                  <ul>
                      <li><a href="#dog1"> dog1</a></li>
                      <li><a href="#dog2"> dog2</a></li>
                      <li><a href="#dog3"> dog3</a></li>
                </ul>
            </li>
        </ul>
    </div>

The idea is to use the clicked element to find the h3 and li that need to be highlighted. Also, in CSS, make the selector more generic so it will apply to both the h3 and li elements.

Comments