简体   繁体   中英

How to assign a class “active” to the li element based on current URL and 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. Right now it is applied only to the index page by default.

My menu snippet:

<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>

Try this code. Its working at my end.

<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>

I think you are looking for this. Tried and tested ,, See the Demo and UPDATED DEMO

    $(".navbar-nav").find("a").click(function(){

               $(".navbar-nav").find("li").removeClass("active");
                $(this).parent("li").addClass("active");




        })

        $( window ).load(function() {


         var which_page=window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
                    $(".navbar-nav").find("a").each(function(){
                    if($(this).attr("href") == which_page)
                    {
                     $(this).addClass("active");

                    }

                   })



        });

UPDATED DEMO

i assume if you are using php ur page would be like this. just define a $active variable in each page.

<?php 
//Main.php
 $active = "Main";
?>

<?php 
//news.php
 $active = "News";
?>

<?php 
//Contacts.php
 $active = "Contacts";
?>

Then your html would be like this.

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

I think this will be better:-

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

Try this jQuery:-

$("div.navbar-nav").on('click', 'li', function() {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
});

If you want to keep last selected value after page load based on anchor tag url then add this lines also.

// get the actual pathname:
var path = location.pathname;
// filter menu items to find one that has anchor tag with matching href:
$('.navbar-nav li').filter(function(){
    return '/' + $('a', this).attr('href') === path;
// add class active to the item:
}).addClass('active');

OR

$(document).ready(function () {
        var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");

        $('.navbar-nav a').each(function () {
            if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
                $(this).parent().addClass('active');
        });
  });

Hope it will help you :)

You can do it in PHP.

Steps:

1) Create a multi-dimensional array of menus.

2) Key is the link and value is the text.

3) Get the current page URL.

4) Get the last segment of the url using basename() .

5) That will be your current page variable. If its blank, assign it to home page.

6) Loop over menus array.

7) Display menu li s in loop.

8) If current loop items is equal to current page, add class active else, add no class.

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
$menus = array();
$menus['main'] = 'index.php';
$menus['news'] = 'News';
$menus['contacts'] = 'Contacts';
$currentURL = curPageURL();// Get Current url here.
$currentPage = basename($currentURL);
$currentPage = empty($currentPage) ? 'main' : $currentPage;
if (! empty($menus)) {
?>
<ul class="nav navbar-nav">
<?php
    foreach ($menus as $lnk => $txt) {
        $activeCls = ($lnk == $currentPage) ? 'active' : '';
?>
     <li class="<?php echo $activeCls;?>"><a href="http://localhost/wp/<?php echo $lnk;?>"><?php echo $txt;?></a></li>
    <?php
    }
?>
</ul>
<?php
}
?>

i hope this would help you 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>

there might be some other way to get current page url or title or id, please check here Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM