How to assign a class “active” to the li click event using jQuery or JavaScript

I am trying to create a menu where a class “active” is assigned to the page whenever it’s selected and loaded and following this using javascript

my menu its custom

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>

Its working at my end use this

<script>
jQuery(document).ready(function() {
    jQuery(".nav.navbar-nav li").click(function(){
        jQuery(".nav.navbar-nav li").removeClass('active');
        jQuery(this).addClass('active');
        })
var loc = window.location.href;
 jQuery(".nav.navbar-nav li").removeClass('active');
    jQuery(".nav.navbar-nav li a").each(function() {
        if (loc.indexOf(jQuery(this).attr("href")) != -1) {

            jQuery(this).closest('li').addClass("active");
        }
    });
});     
</script>

<ul class="nav navbar-nav">
     <li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
     <li><a href="http://localhost/wp/news">News</a></li>
     <li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>

this will be better

$(".navbar-nav").children("a").click(function(){
    $(".navbar-nav").children("li").removeClass("active");
    $(this).parent("li").addClass("active");
 })

if you can edit your theme

$slug = basename(get_permalink());

<ul class="nav navbar-nav">
         <li class="<?php echo $slug =='Main_page_slug'? 'active' : ''; ?>"><a href="http://localhost/wp/index.php">Main</a></li>
         <li class="<?php echo $slug =='newpageslug'? 'active' : ''; ?>"><a href="http://localhost/wp/news">News</a></li>
         <li class="<?php echo $slug =='congtactPageslug'? 'active' : ''; ?>"><a href="http://localhost/wp/contacts">Contacts</a></li>
    </ul>
Social Share

Leave a Comment