Akhilesh Sehgal Akhilesh Sehgal - 2 months ago 9
jQuery Question

Adding a class to body when a Hyperlink tag is clicked which is in the child ul of li tag using jquery

I want to add a class to body when a link is clicked. This is easily done when the link is in the parent ul, but my problem is that i want to do that for the the link present in the child ul of parent li. Whenever I try to do this It has no effect.
What I am trying to do is as given below:
Script:

<script>
$(document).ready(function () {
$("ul.treeview-menu").find("a.links").click(function () {
$("body").addClass("sidebar-collapse");
});
});
</script>

<ul class="sidebar-menu nav nav-list" id="dashboard-menu">
<li class="treeview">
<a rel="tooltip" data-placement="right" target="_self" href="">
<span class="caption">Parent Link</span>
</a>
<ul class="treeview-menu">
<li>
<a href="any-link" target="_self" class="links">child link</a>
</li>
</ul>
</li>
<ul>


Thank you in advance.

Answer

Try with on('click',...), may be your Navigation will generate dynamically after load page so you have to use delegated event binding

  $(document).ready(function () {
    $(document).on('click','ul.treeview-menu a.links',function () {
        $("body").addClass("sidebar-collapse");
    });
  });



<ul class="sidebar-menu nav nav-list" id="dashboard-menu">
    <li class="treeview">
         <a rel="tooltip" data-placement="right" target="_self" href="">
             <span class="caption">Parent Link</span>
          </a>
          <ul class="treeview-menu">
               <li>
                     <a href="abc" target="_self" class="links">child link</a>
               </li>
          </ul>
    </li>
 <ul>