1
votes

I am adding class="active" in nav > ul >li by jQuery for changing background color . Its working when href="#" . But when I am adding link in between href="example.php" - its go to the page . but active class is not working and background is not remaining to show where I am .

is it possible link work and also background change to show which page I am now by jQuery or how they do in WP ?

$(document).ready(function(){
$(".menu").on('click','li', function(){
    $(".menu .active").removeClass('active');
    $(this).addClass('active');

} );

} );

<ul class="menu">
    <li class="active"><a href="index.php">Home</a></li>
    <li><a href="bestdeal.php">Best Deal</a></li>
    <li><a href="#">Shop</a>
        <ul>
            <li><a href="#">Sub menu</a></li>
            <li><a href="#">Sub menu</a></li>
        </ul>
    </li>
    <li><a href="#">About Us</a>
        <ul>
            <li><a href="#">Sub menu</a></li>
            <li><a href="#">Sub menu</a></li>
        </ul>
    </li>
    <li><a href="#">Contact Us</a></li>
</ul>
2
Your class is most likely getting applied, but then the page navigation occurs leaving your styles on the previous page. You could check the url on page load and check for any .menu > li > a with a matching href and re-apply the style. - Nicolay

2 Answers

1
votes

You could try checking to see if the page href matches your link exactly, in the case that it is not a # link.

$(document).ready(function(){
  var $links = $('.menu li a');
  
  $links.closest('.active').removeClass('active');
  
  $links.filter(function(){
    return this.href === window.location.href;
  }).closest('li').addClass('active');
});
.active a { color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
    <li class="active"><a href="index.php">Home</a></li>
    <li><a href="/js">My Amazing Code Snippet on Stack Overflow</a></li>
    <li><a href="#">Shop</a>
        <ul>
            <li><a href="#">Sub menu</a></li>
            <li><a href="#">Sub menu</a></li>
        </ul>
    </li>
    <li><a href="#">About Us</a>
        <ul>
            <li><a href="#">Sub menu</a></li>
            <li><a href="#">Sub menu</a></li>
        </ul>
    </li>
    <li><a href="#">Contact Us</a></li>
</ul>
0
votes

Yeah, it's a little tricky when you are changing pages - you need a way to send the clicked-on identifier to the new page. Most times we can use a bit of jQuery to do that. (The jQuery will interrupt the default <a> action, create a <form> with a hidden field that contains the information you want to send, and then submit() the form)

But there might be a simpler way... For each page, just make THAT page's menu item have the active class.

If the simple way doesn't work, this SO answer has a demo that should work for you:

How to pass data to another page using jquery ajax