Deepak Deepak - 4 days ago 5
jQuery Question

How To Highlight Parent <Li> When Child <Li> Is Active using jquery

I have a sidebar which include links and sub links.

Here is my code -



<div id="mySidenav" class="sidenav">
<ul style='list-style:none;'>
<li><a href="<?php echo site_url('admin/dashboard'); ?>">Dashboard</a></li>
<li id='post_list'> <a href="#">Posts</a>
<ul style='list-style:none;' id='sub_links'>
<li><a href='<?php echo site_url('admin/all_posts'); ?>'>All</a></li>
<li><a href='<?php echo site_url('admin/add_post'); ?>'>Add</a></li>
<li><a href='<?php echo site_url('admin/post_categories'); ?>'>Category</a></li>
</ul>
</li>
<li id='post_list'> <a href="#">Pages</a>
<ul style='list-style:none;' id='sub_links'>
<li><a href='<?php echo site_url('admin/all_pages'); ?>'>All</a></li>
<li><a href='<?php echo site_url('admin/add_page'); ?>'>Add</a></li>
</ul>
</li>
<li><a href="#" class='media_upload'>Media</a></li>
<li id='post_list'> <a href="#">User</a>
<ul style='list-style:none;' id='sub_links'>
<li><a href='<?php echo site_url('admin/all_users'); ?>'>All</a></li>
<li><a href='<?php echo site_url('admin/add_new_user'); ?>'>Add</a></li>
<li><a href='<?php echo site_url('admin/user_profile'); ?>'>Profile</a></li>
</ul>
</li>
<li><a href="#">Setting</a></li>
<li><a href="<?php echo site_url('admin/logout')?>">Logout</a></li>
</ul>
</div>
</div>
</div>
</div>





My question is how to set active class to parent li when it's child li is clicked?

Thanks.

Answer

First of all, your ids must be uniqe! And if I were you I would change id attribute to class, like so:

<div id="mySidenav" class="sidenav">
  <ul style='list-style:none;'>
    <li>
      <a href="<?php echo site_url('admin/dashboard'); ?>">Dashboard</a>
    </li>
    <li class='post_list'> 
      <a href="#">Posts</a>
      <ul style='list-style:none;' class='sub_links'>
        <li>
          <a href='<?php echo site_url(' admin/all_posts '); ?>'>All</a>
        </li>
      </ul>
    </li>
  </ul>
</div>


And then in your JS file:

$(".sub_links li").on("click", function(){
    $(this).closest(".post_list").addClass('active');
});

Here you go, should work

Comments