Aber LINKS Website – Colouring Nav Links

To let the user know which page they are on, I wanted the corresponding link in the nav bar to be different to indicate that they were on that page. Until now, I thought the only way would be having a separate nav bar for each page, each with one link as a certain style.

A few days ago, I had an idea – can PHP determine what page it is on (almost like Java’s Reflection). It turns out yes, yes it can! I was talking to a colleague and they had just implemented what I had been thinking about, and a short time later, it is all done and working. I first tried underlining the current nav location with a large orange line, and then colouring the background grey – but neither looked too good. I had the idea of making the background white with black text so that it looked like the top tab of the current page. This wasn’t easy to implement as I was trying to style an anchor that did not want to change it’s colour. In the end I chose to surround each nav item with a div – “highDiv” or “lowDiv” depending on if they were on that page that link points to or not.

Example of highlighted nav item

The vital code for each of my nav items is:

<li><div <?php if(basename(strtolower($_SERVER['SCRIPT_NAME'])) == ‘index.php’) {echo ” id=\”highDiv\”";} else  {echo ” id=\”lowDiv\”";} ?>><a href=”index.php”>Home</a></div></li>

Explanation:

Each nav item is a list item, and inside that thre is a div – the id of which is controlled by PHP. The PHP asks if the SCRIPT_NAME (page name) is equal to ‘index.php’ (for the “Home” link), and if so, it will give the div the id “highDiv” – which colours the background white and the text black. If that statement is false, it will give it the id of “lowDiv” – just normal.

I have a feeling this could be streamlined by using an array of pages (replace the index.php with pageArray[i] in a big for loop) and an array of link texts [to replace "Home" etc]. I assume this is what people do for big sites that have changing link menus.

Hope this helps!

Matt