What\'s the quickest and easiest way to add the \"active\" class to a link, so it can be styled? I\'m developing an app in CI, and I\'d like a quick easy way to do this automat
Depends on how you're outputting your link HTML.
If you're using the URL Helper module, then you can call the anchor()
function to create your links, and pass it an array of attributes as the third parameter, ie:
$this->load->helper('url');
echo anchor('url/path', 'Click here', array('class' => 'active'));
If you're just outputting the HTML manually in your templates/views, obviously you can just create the class attribute yourself in the HTML.
To adding active class (class=”active”) to a link , I’ve done it by doing this:
In view
<ul class="nav nav-tabs">
<li id="button_home" class='<?php echo $home;?>'><?php echo anchor('pages/index','Home');?></li>
<li id="button_about" class='<?php echo $about;?>'><?php echo anchor('pages/about','About')?></li>
</ul>
In controller
$data['home']="active";
Maybe it's not your solution. but it works for me.
You can do this way by creating helper with following
<?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' : '';
}
}
then apply it in menu view
<li class="<?php echo active_link('services'); ?>"><a href="<?php echo base_url();?>services">Services</a></li>
You should really be using the CodeIgniter URI Class to do this instead of the $_SERVER['REQUEST_URI']
$this->uri->uri_string()
if ( $this->uri->uri_string() == '/contact' )
^^ that is the preferred way to do things due to some complexities that can happen with codeigniter's routing features
If you have a lot of navigation items you can do it this way (very simplified)...
<ul>
<li<?= if ( $_SERVER['REQUEST_URI'] == '/contact' ): ?> id="active"<?php endif; ?>><a href="">contact</a></li>
</ul>
You'll have to edit it for your needs...
If you don't have that many nav items an easier way is to give each page a body id and then use css to make it active.
<style type="text/css">
body#contact #contact-nav { font-weight:bold; }
</style>
<body id="contact">
<ul id="navigation">
<li id="contact-nav"><a href="">contact</a></li>
</ul>