Add active class to menu in codeigniter

Rakesh Sharma      1 Comment  

Add active class to menu in codeigniter :-

In codeigniter it’s easy to add active class to current menu or highlight current page in menu item. so we can check which page we have.
i am using helper to active current menu or add active class to menu in codeigniter.
We need to follow some steps to highlight current page in menu or get current page to add active class in codeigniter.
let’s see how to add active class to menu in codeigniter.

1. Create a file named “menu_helper.php” under “application/helpers/menu_helper.php” and add below code.

<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
if(!function_exists('active_link')) {
  function activate_menu($controller) {
    // Getting CI class instance.
	$CI = get_instance();
    // Getting router class to active.
    $class = $CI->router->fetch_class();
    return ($class == $controller) ? 'active' : '';
  }
}?>

2. Load above helper in autoload (go to config/autoload.php and add below code or add “menu” helper in existing helpers)

$autoload['helper'] = array('menu');

3. Add class to your menu. pass your controller name in activate_menu()

<li class="<?php echo activate_menu('home'); ?>"><a href="<?php echo site_url();?>">Home</a></li>
<li class="<?php echo activate_menu('contact'); ?>"><a href="<?php echo site_url('contact');?>">Contact us</a></li>

4. Make an active class in css or rename return ($class == $controller) ? ‘active’ : ”; active to your class to add on activation link.

Now go to your menus and click on it you get highlighted your menu with active class you added.