Is there a php or javascript code that can detect the current user's page and then add <a class="active"> to an item in a ul (my menu). I include my menu in my pages with PHP include so making change is easy; I only have to edit it once. But, with that method, I can't individually set each page to have a class="active". How can I do this?
views:
61answers:
3
A:
In PHP, you can look at the value of $_SERVER['REQUEST_URI'].
In JavaScript, you can examine window.location.
m1tk4
2010-07-25 15:00:34
I'm not that great with either of those languages. How exactly would I do that?
Christopher
2010-07-25 15:01:06
+1
A:
You several options, e.g.,
- The part that handles navigations can read the request URI directly. This can be done by reading
$_SERVER['REQUEST_URI'](don't forget this may include the query string). - At some point, you must know what page you're on, because you decide which content you display based on that. You can define a function that handles the navigation markup and pass it the name of the current page so that it knows which one it is.
Artefacto
2010-07-25 15:02:56
+1
A:
If I'm understanding your question correctly, what I usually do is set a variable before I include the header, like
$current = "home";
And then in the header I'd have an if statement in each link
<a href="/home" <?php if ( $current == "home" ) { echo "class='active'" } ?>>Home</a>
Could be ways to improve it, but it's simple if your menu isn't too big.
Ryan
2010-07-25 16:58:47