Monday, June 27, 2016

One Page Menu System

I thought it would make sense to make my first article in this blog be about how to make a simple menu system.

You wouldn't use this menu on a "public" site, this menu is well suited for a Content Management System (CMS). Rather than writing a menu for each section of your site you can create one page that contains all the menus.

You can also apply this same concept to any page that you would like to be different based on how the page was entered.

It's done using very basic PHP and CSS.

The strategy is a simple one. Create a container to hold the menu system, create a container for each menu and then display the one you need.

<div id="menu-display">
   <div id="main">
       <a class="menu-entry" href="index.php?menu=user">User Menu</a>
       <a class="menu-entry" href="index.php?menu=system">System Menu</a>
   </div>
   <div id="user">
       <a class="menu-entry" href="user1.html">User Page 1</a>
       <a class="menu-entry" href="user2.html">User Page 2</a>
       <a class="menu-entry" href="user3.html">User Page 3</a>
       <a class="menu-entry" href="index.php">Main Menu</a>
   </div>
   <div id="system">
       <a class="menu-entry" href="system1.html">System Page 1</a>
       <a class="menu-entry" href="system2.html">System Page 2</a>
       <a class="menu-entry" href="system3.html">System Page 3</a>
       <a class="menu-entry" href="index.php">Main Menu</a>
   </div>
</div>

The "menu-display" <div> is the container that holds all the menus. Style this for color, font, etc and your menus will all look the same.

The "main", "user", and "system" <divs> are the individual menus. It doesn't matter what order they are in unless you plan to display 2 at once. An example would be additional menu items available only to certain users.

So how do you make things appear and disappear? That is where PHP is your friend, it just takes a couple lines of code.

At the top of your page:

<?PHP

$display = "main";

if (isset($_GET['menu']) { $display = $_GET['menu']; }

?>

In the above the variable $display is set to "main". So if the page is called without any menu request, it will default to the main menu.

The next line checks to see if a menu name was passed to the page. If so, then the $display variable is changed from the default.

The following code is then executed at the bottom of the <head> section of the page. Just before the </head> closing tag.

<style>
  <?PHP
    if ($display != "main") { echo "#main { display: none"; }
    if ($display != "system") { echo "#system { display: none"; }
    if ($display != "user") { echo "#user { display: none"; }
   ?>
</style>

The above is a simple set of statements that checks the $display variable and sets the <div> to not be displayed if there is not a match. If you have a large number of menus you could easily use a loop to accomplish the task.

You can see a working example and download the code here.