The problem:
A while back I was struggeling with my menu. I couldn't get my menu buttons to stay in active state without adding a diffrent id or class to my body tag on every page. Now that I found a way to do this without giving id's to my button's, I thought I'd share it with you.
btw this is my first tutorial ever and english is not my native language, so bare with me if everything is a bit chaotic.
Let's get starded:
The code i starded of with was a basic list menu, styled with CSS.
<ul class="main_menu"> <li><a href="index.php">Home</a></li> <li><a href="portfolio.php">portfolio</a></li> <li><a href="aboutme.php">About me</a></li> <li><a href="blog.php">Blog</a></li> <li><a href="contact.php">Contact</a></li> </ul>
To know on which button needs to be active we need to know what page we are on, so first thing we need to do is get the url of the current page.
this can be done with a simple php command.
$_SERVER["REQUEST_URI"]
this gives the full url of the current url, for example.
Quote
This is great now we know which page we are on. We only need the last tiny bit of the url though to know which button need to be active. to get this part we can use the following php code.
basename($_SERVER["REQUEST_URI"])
Now that we have the information we need we can start to make our menu.
<ul class="main_menu"> <li <?php if (basename($_SERVER["REQUEST_URI"]) == "index.php") echo " class='active_link' ";?> ><a href="index.php">Home</a></li> <li <?php if (basename($_SERVER["REQUEST_URI"]) == "portfolio.php") echo " class='active_link' ";?>><a href="portfolio.php">portfolio</a></li> <li <?php if (basename($_SERVER["REQUEST_URI"]) == "aboutme.php") echo " class='active_link' ";?>><a href="aboutme.php">About me</a></li> <li <?php if (basename($_SERVER["REQUEST_URI"]) == "blog.php") echo " class='active_link' ";?>><a href="blog.php">Blog</a></li> <li <?php if (basename($_SERVER["REQUEST_URI"]) == "contact.php") echo " class='active_link' ";?>><a href="contact.php">Contact</a></li> </ul>
The above code checks if the the current page is the same as the link and if it is it adds the class active. Now we can simply style our active button with css.
.active a:link {
background-image: url(images/button_active.jpg);
}That's it. Your menu should now have cool shiny active buttons
Problems:
I understand that this menu is far from perfect and it won't work on large websites. I just found it very usefull on my small website projects. It keeps things very dynamic and easy to change.
For the people who use subfolders for every page you can use
basename(dirname($_SERVER["REQUEST_URI"]))to get the foldername ( this method probably works better if your site gets larger )
Well i would like to thank you all for reading. Feedback/ questions about this tutorial is apriciated.
Help



















