0

I have a small php website that has a menu that is included via include_once. I need an HTML class added to the current menu item for each page.

So if a user clicks on a link and goes to that page the new page will load with the new menu item with class="current". How can I go about doing this?

1
  • 6
    Pretty hard without seeing any of your code, please consider adding your html for the menu and how it is generated in your php; also, how you tell the current page ($_GET array or other) Commented Oct 19, 2011 at 14:39

1 Answer 1

1

Let's say you write your menu like this:

<ul>
<li><a href="link1.com?menu=1"> Link1 </a></li>
<li><a href="link2.com?menu=1"> Link2 </a></li>
<li><a href="link3.com?menu=1"> Link3 </a></li>
</ul>

Here is a good old php4 style solution :-p

<?php
//you get which link was clicked
if(isset($_GET['menu']) $menu = $_GET['menu'];
else $menu = 1;

$1 = $2 = $3 = ""; //you create 3 empty strings
switch($menu){ //you assign the correct string with your css class name
case "1": $1 = 'class="current"';break;
case "2": $2 = 'class="current"';break;
case "3": $3 = 'class="current"';break;
}
?>
//echo the variables into the menu anchors ( <?=$1?> is equivalent to  <? echo $1; ?> )
<ul> 
<li><a href="link1.com?menu=1" <?=$1?> >Link1</a></li>
<li><a href="link2.com?menu=2" <?=$2?> >Link2</a></li>
<li><a href="link3.com?menu=3" <?=$3?> >Link3</a></li>
</ul>

You can also place the <?=$1?> into the <li> or anywhere else wanted...

If you're using javascript in your project, you could also give an id to your anchors (like <a href="link1.com?menu=1" id="link1">Link1</a>), get the menu value like above with $_GET, and then use javascript to add the class to the desired link.

I gave you this answer because from what you're writing I guess you're not using any PHP framework but coding you app the old way... there's plenty of nice PHP framework around here that will have pre-made solution for this... might be hard at the beginning but it's worth it...

Good luck!

Sign up to request clarification or add additional context in comments.

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.