0

In my php web project, I want to add a CSS class (.active) to the current url route when the user clicks on the navigation menu bar, i.e. my navigation menu.

<li><a href="http://localhost:8000/OhdyDaran')">Designation</a></li>
<li><a href="http://localhost:8000/gallery">Gallery</a></li>
<li><a href="http://localhost:8000/Introduction">introduction</a></li>
<li><a href="http://localhost:8000/home">Home</a></li>

How to Make an Application.active CSS class with Jquery or JS, after page refresh, is the link css applied?

3 Answers 3

4

Try this.

$(document).ready(function () {
   var link = window.location.href.split('/');
   var page = link[link.length - 1];
   var url = link[link.length - 2];

   // now select the link based on the address
   $('li > a[href="'url + '/' + page + '"]').closest('li').addClass('active');
            })
Sign up to request clarification or add additional context in comments.

5 Comments

thanks to reply, its working fine, problem another here, after page refresh active class disappear ? how fix it
@saeedahmed it working perfectly after page refresh.
I check it again, when I click on anchore tag class is applied. the page go to server side after response it disappeared again
$(function(){ $('.nav a').filter(function(){ return this.href==location.href}).parent().addClass('active').siblings().removeClass('active') $('.nav a').click(function() { $(this).parent().addClass('active').siblings().removeClass('active') }) });
thanks above code that I pasted here is working perfectly :)
2

You can get the url or path in this way:

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

And then, if the url or path is the same as the link, give it the .active class.

1 Comment

plz write complete code, there is confusion what u want to say ?
1
<li class="ohdyDaran">
    <a href="http://localhost:8000/ohdyDaran')">Designation</a>
</li>
<li class="gallery">
    <a href="http://localhost:8000/gallery">Gallery</a>
</li>
<li class="introduction">
    <a href="http://localhost:8000/introduction">introduction</a>
</li>
<li class="home">
    <a href="http://localhost:8000/home">Home</a>
</li>

<script>
var url = window.location.href;
    var last = url.split('/');
    var clas= last[last.length-1];
    var nav = document.getElementsByClassName(clas)[0];
    nav.className = "active";
</script>

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.