how to add active class in menu using jquery?

how to add active class in menu using jquery : How to get the URL of the current page using and adding an active class to navigation based on URL. Simply way to Add active menu class based on URL using jQuery Example

how to add active class in menu using jquery

jQuery add active class to ul li menu tag on click. you’ll learn how to add an active class to a menu item based on the page URL using jQuery with source code.

$("#mainMenuNavigation").on('click','li',function(){
     $(this).addClass("active");  // adding active class
});

here delete classname ‘active’ from all li who already has classname ‘active’ and adding classname ‘active’ to current click li.

Read Also:  how to get javascript variable value in php in same page?

$("#mainMenuNavigation").on('click','li',function(){
    
    $("#mainMenuNavigation li.active").removeClass("active"); 
    $(this).addClass("active"); 
});

Jquery Add active class to main menu

index.html

<body>
  <div style="text-align:center;margin-top:25px;font-weight:bold;texxxt-decoration:none;">
  Visit <a href="https://themeshook.com/" px;target="_blank">My Blog</a>
</div>
  <div class="container">
      <nav class="navecation">
       <ul id="navi">
    <li><a class="menu active"#">About </a></li>
    <li><a class="menu" href="#">Contact  </a></li>
         <li><a class="menu" href="#">Services</a></li>
    <li><a class="menu" href="#">New Product</a></li>          
    <li><a class="menu" href="https://www.pakainfo.com/laravel-add-active-class-nav-menu-system/">Read Our Blog</a></li>
  </ul>
    </nav>
  </div>
</body>

style

body{
  font-sze:14px;
}

.container{
 max-width:960px;
  margin:0 auto;
}
nav ul li{
  list-style:none;
  float:left;
  padding-right:20px;
}
nav ul li a{
  text-decoration:none;
  color:#222;
  background-color:#ccc;
  padding:4px 5px;
}
.active{
  background-color:#d90000;
  color:#fff;

}
 

jquery

$(document).ready(function(){
  $('ul li a').click(function(){
    $('li a').removeClass("active");
    $(this).addClass("active");
});
});

Add Active Navigation Class Based on URL

<nav>
	<ul>
		<li><a href="/">Blog</a></li>
		<li><a href="/about/">About</a></li>
		<li><a href="/jobs/">Jobs</a></li>
		<li><a href="/new_product/">New Product</a></li>
	</ul>
</nav>	

https://www.pakainfo.com/about/team/

Read Also:  JavaScript Remove Duplicate values from Array

$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

Don’t Miss : jQuery add active class to current page

I hope you get an idea about how to add active class in menu using jquery.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.