0

I'm using single navigation file for all web pages, so i need to add or remove class based on click function. but somehow it's not working fine. any help would be appreciated.

$(function() {
  $("li").on("click", function() {
    $("li.active").removeClass("active");
    $(this).addClass("active");
  });
});
<div class="nav-side-menu">
  <div class="brand">Brand Logo</div>
  <i class="fa fa-bars fa-2x toggle-btn" data-toggle="collapse" data-target="#menu-content"></i>
  <div class="menu-list">
    <ul id="menu-content" class="menu-content collapse out">
      <li style="cursor: pointer;" onclick="window.location='new-patient.php';">
        <a><i class="fa fa-plus-square"></i>New Patient</a>
      </li>
      <li style="cursor: pointer;" onclick="window.location='returning-patient.php';">
        <a><i class="fa fa-plus-square"></i>Returning Patient</a>
      </li>
    </ul>
  </div>
</div>

3
  • When page is navigate to other page then how you can manage active state from old page. for this you have to change your code Commented Oct 5, 2017 at 9:22
  • based on the url you can manage which li need to be active. This is only the solution Commented Oct 5, 2017 at 9:24
  • If you are using php ( from the window location attr in your code ), it's better to handle the class when rendering the page itself instead of handling it later on via javascript Commented Oct 5, 2017 at 9:30

2 Answers 2

2
$('#menu li a').on('click', function(){
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

You can use following script on every page to set this.

var pageName = (function () {
  var a = window.location.href,
    b = a.lastIndexOf("/");
  return a.substr(b + 1);
} ());

$("#menu-content a").each(function () {
  if ($(this).attr('href') == pageName) {
    $(this).parents("li").addClass('active');
  }
})	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-side-menu">
	<div class="brand">Brand Logo</div>
	<i class="fa fa-bars fa-2x toggle-btn" data-toggle="collapse" data-target="#menu-content"></i>
	<div class="menu-list">
		<ul id="menu-content" class="menu-content collapse out">
			<li>
				<a href="new-patient.php">
					<i class="fa fa-plus-square"></i>New Patient
				</a>
			</li>
			<li>
				<a href="returning-patient.php">
					<i class="fa fa-plus-square"></i>Returning Patient
				</a>
			</li>
		</ul>
	</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.