Monday, July 10, 2017

How to add active class to codeigniter hyperlinks

In the previous article, I showed How to add the active class to the menu in CodeIgniter. Now I am going to show another process to do this. At first, you need to create a helper class. I created this file in 'helpers' called 'nav_helper.php'.
helpers/nav_helper.php
<?php  if(!defined('BASEPATH')) exit('No direct script access allowed');
if (! function_exists('active_link')){
    function active_link($controller){
        $CI =& get_instance(); 
        $class = $CI->router->fetch_class();
        return ($class == $controller) ? 'active' : '';
    }
}
Load the file: You can load this file via the controller..
$this->load->helper('nav');
Or you can also load directly putting it above the view file with the php tags.
<?php $this->load->helper('nav'); ?>
The view file:
      <ul>
        <li class="<?php echo active_link('about'); ?>"><a href="<?php echo site_url('about'); ?>">About</a></li>  
        <li class="<?php echo active_link('contact'); ?>"><a href="<?php echo site_url('contact'); ?>">Contact</a></li>
      </ul>
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, discuss with team members to solve quickly.