2

I try to add class in li tag but it's not able to add via javascript function but it's just append on li tag while page is loading then it is disappeared. Can you ju help us how can i solve it?

active class is not set while we are selected to while we are click to one menu

html code

<div class="side-bar-wrap sidbr" id="sideBarsec"> 
<nav class="side-bar" style="width: 325px;background:linear-gradient(0deg, #37C4AA,#0B99A7);height:1382px;;">
  <div class="logo-area">  
    <a href="{% url 'home' %}">
      <img src="{% static 'website/vendors/images/Rectangle_33.png' %}" alt="" style="width: 176px; height:58px" />
    </a>
  </div>
  <ul class="menu" id="navMenus">
    <li class="homeicn nav-item">
      <a href="{% url 'home' %}">
        <span class="title menutitle">Client</span>
      </a>
    </li>
    <li class="medicalicn nav-item">
      <a href="#">
      <span class="title menutitle">Medical</span>
      </a>
    </li>
    <li class="socialicn nav-item">
      <a href="#">
        <span class="title menutitle">Social</span>
      </a>
    </li>
    <li class="transporticn nav-item">
      <a href="#">
        <span class="title menutitle">Transportation</span>
      </a>
    </li>
    <li class="activityicn nav-item">
      <a href="#">
        <span class="title menutitle">Activity</span>
      </a>
    </li>
    <li class="foodicn nav-item">
      <a href="#">
        <span class="title menutitle">Food</span>
      </a>
    </li>

    <li class="reportsicn nav-item">
      <a href="#">
        <span class="title menutitle">Reports</span>
      </a>
    </li>

    <li class="scheduleicn">
      <a href="{% url 'schedule' %}">
        <span class="title menutitle">Schedule</span>
      </a>
    </li>
    
  </ul>
</nav>
 </div>
 script code
  <script>
     $("#navMenus").on('click', 'li', function () {
  alert("in navMenus click");
$("#navMenus li.active").removeClass("active");
// adding classname 'active' to current click li 
$(this).addClass("active");
 });
   </script>
       
KrupaV
  • 81
  • 4
  • 1
    it could be because the link is redirecting to a new page so the class is being removed? – Pete Oct 11 '22 at 10:16
  • not sure may be it could happened... but if it is then how can I solve it? – KrupaV Oct 11 '22 at 10:18
  • You could do something like this (but I would use local or session storage instead of a cookie) https://stackoverflow.com/questions/20351590/jquery-onclick-but-do-action-after-page-reload or you might want to add the class based on your url: https://stackoverflow.com/questions/20060467/add-active-navigation-class-based-on-url – Pete Oct 11 '22 at 10:21

1 Answers1

0

Try to write your jQuery code inside a document.ready

$(document).ready(function(){
     $("#navMenus").on('click', 'li', function () { 
        alert("in navMenus click");
        $("#navMenus li.active").removeClass("active");
        // adding classname 'active' to current click li 
        $(this).addClass("active");
     });
});