Add active class to current link in codeigniter

If you are working with codeigniter or with any other language or framework, this is a common need to add active class to current link or highlight current page menu item. So in this article we will see different ways to add active class to current link in codeigniter. We will done this by using codeigniter Helpers.

Create helper

To add active class to current link in codeigniter first we need to create a helper file under application/helpers/active_helper.php. So we creating a helper with named active_helper.php. Now add below code in active_helper.php.

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

Load helper

Now we need to load this helper in our project so we can get this function on all our site. For add globally just we need this in application/config/autoload.php. Add helper in autoload under $autoload['helper'] array().

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

If you want to load this helper in separate file and don’t want to use globally. Just add below code in controller class function.

$this->load->helper('active');

Call from view

Now we need to call this function from our view file where we have link to add active class to current link. so call the function like below

<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>

Conclusion

So you easily can add active class to current link in codeigniter using helper function. I tried to show simple ways. Hope this will enough information to get this task done. If you have any issues let me know through comment.

Cheers! Happy coding!

Adam Brown
Please follow and like us:

Leave a Comment