Pages

Sunday, 26 May 2013

Apply active class on menu using php

When a menu item is clicked and is active, what's the best way to style it differently? Lets create a dynamic menu bar with the help of php.

Step 1:Create a html page with menu items

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Html,Css,Php Menu</title>
<style type="text/css">
div.menu li{
    float: left;
    padding: 0 4px 0 0;}


/*  create active class that are used when menu is clicked */

.active{
    background: none repeat scroll 0 0 #636363;
    border-color: #636363 #636363 -moz-use-text-color;
    border-style: solid solid none;
    border-width: 1px 1px medium;
    color: #FFFFFF;
}  

</style>
</head>

<body>
<div class="menu">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About Us</a></li>
<li><a href="contact.html">Contact Us</a></li>
<li><a href="services.html">Services</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
</div>
</body>
</html>

 


Step 2: Create some php code that are usen in header

<?php 

$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);

// this give value in array we take first value because on array 0 wiil contain your domain name
 $first_part = $components[1];
?>


Step 3: Now apply php code in html menu bar

<div class="menu">
<ul>
<li><a class="<?php if ($first_part=="
index.html") {echo "active"; } ?>" href="index.html">Home</a></li>
<li><a
class="<?php if ($first_part=="about.html") {echo "active"; } ?>" href="about.html">About Us</a></li>
<li><a
class="<?php if ($first_part=="contact.html") {echo "active"; } ?>" href="contact.html">Contact Us</a></li>
<li><a 
class="<?php if ($first_part=="services.html") {echo "active"; } ?>" href="services.html">Services</a></li>
<li><a
class="<?php if ($first_part=="
blog.html") {echo "active"; } ?>" href="blog.html">Blog</a></li>
</ul>
</div>


Copy and paste this div into your page where you create html menu.

No comments: