Thursday, June 22, 2017

How to add active class to menu in codeigniter

CodeIgniter: How to 'highlight' the link of the page the user is currently on? If you are new CodeIgniter user this may your question. There are many tricks to highlight active menu link of CodeIgniter framework. Here is a very simple trick to do this. At first you need to create a helper class. I crated this file in 'helpers' called 'menu_helper.php'.
    function menu_anchor($uri = '', $title = '', $attributes = ''){
        $title = (string) $title;

        if ( ! is_array($uri)){
            $site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
            $site_url = site_url($uri);

        if ($title == ''){
            $title = $site_url;

        if ($attributes != ''){
            $attributes = _parse_attributes($attributes);
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $attributes .= ($site_url == $current_url) ? 'class="active"' : 'class="normal"';
        return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
Load the file: You can load this file via the controller..
Or you can also load directly putting it above the view file with the php tags.
<?php $this->load->helper('menu'); ?>
The view file:
<?=menu_anchor(base_url()."controller_name", "Home")?>
<?=menu_anchor(base_url()."controller_name", "About")?>
<?=menu_anchor(base_url()."controller_name", "Contact")?>
<?=menu_anchor(base_url()."controller_name", "Privacy")?>
The css:
.active{background-color:#16A085;color:#fff !important;}

How to practice tutorials…

  • Make a team with your friends (Member should be 4/5).
  • Start to practice one tutorial series along with them.
  • Don’t try to collect source code. Type the code while watching the tutorial.
  • If you face any problem, post the question in the Forum with the error codes.
  • Share that question Link with your friends or team members to solve quickly.
  • Discuss the problem in the Forum along with others - Video Guidelines.