All of the work I’ve done so far has just been with the home page of the website, but what about the other ones? We’ll get into creating those very soon, but first we need to fix up the navigation bar we created weeks ago.
Te navigation bar we have now is fine for jumping from one page to another. But what if we scrolled down to the point where we couldn’t see much of the info on the page and were wondering which page we’re on. The way to fix this is using some javascript to add a class to the current page that makes the text in the link for that page a different color than the rest.
This is the code that I used for it (put inside of my header file, so it applies to each page):
$(function(){
var current = location.pathname;
if (current == “/”)
{$(‘#nav li a[href=”/”]’).addClass(‘active’);}
else{
$(‘#nav li a’).each(function(){
var $this = $(this);
if($this.attr(‘href’).indexOf(current) !== -1){
$this.addClass(‘active’);
}
})}
});
location.pathname grabs anything in the url past the main domain name. For example, calling location.pathname on google.com/images will give you “/images/”. In the case of a domain without any extras, google.com, you will just get a forward slash, /. The “if” statement in the start of the code checks for this to see if it should add the class to the “Home” link. Everything in the “else” statement will check which link to add the class to based on the “href” part of the link.
The “active” class is simply a class with the attribute color (set to whatever color you want). In my case I chose gold.
If you want to see this in action create a new php file called photos.php in your /xampp/htdocs/ directory. Include your header and footer to it, with a <div> with the id “content-area” in between. Now just make sure the “Photos” link in your navigation bar has the link “/photos.php”. When you click on “Photos” it should now take you to that page you just created, and “Photos” should be highlighted in your navigation bar, like this:



