Welcome Guest, Not a member yet? Register   Sign In
Add Class to Active Menu Item
#1

[eluser]Barwick[/eluser]
Would this be a suitable option to add an "active" class to a menu item?
Seems like the best option with the least amount of code or controller modifications. As all I'd have to add this too would be the menu view...

Thoughts?

Code:
<ul>
<li class="&lt;?=($this-&gt;uri-&gt;segment(1)==='alfa')?'active':''?&gt;"><a href="alfa/index" title="Alfa">Alfa</a></li>
<li class="&lt;?=($this-&gt;uri-&gt;segment(1)==='beta')?'active':''?&gt;"><a href="beta/index" title="Beta">Beta</a></li>
</ul>
#2

[eluser]Mr. Pickle[/eluser]
Yes, this is an easy way to implement such a thing without too much hassle.
If this is sufficient for you there's nothing against it.
#3

[eluser]Barwick[/eluser]
Perfect! Thanks. Just want to make sure I'm not creating or adapting any bad habits. Cheers!
#4

[eluser]Beginers[/eluser]
wow thanks for sharing this Mike i have been searching of this for so many days. Thanks a lot.
#5

[eluser]Aken[/eluser]
You don't need the index portion of the link, though.
#6

[eluser]Mr. Pickle[/eluser]
Of course you can really make it easy by creating a helper function that does the job so you don't have to repeat the if statements all the time.

Just a rough idea:

helper, e.g. /helpers/MY_navigation_helper.php:
Code:
function get_nav_class($slug)
{
    $CI =& get_instance(); // get instance of CI when putting this code in a helper
    if($CI->uri->segment('1') == $slug)
    {
        $class = 'active';
    }
    else
    {
        $class = '';
    }

    return $class;
}

And then in the view file:
Code:
&lt;? // activate the url helper to make anchor() available ?&gt;
<ul>
  <li class="&lt;?=get_nav_class('alfa');?&gt;">
    <a href="&lt;?=anchor('alfa');?&gt;" title="Alfa">Alfa</a>
  </li>
  
  <li class="&lt;?=get_nav_class('beta');?&gt;">
    <a href="&lt;?=anchor('beta');?&gt;" title="Beta">Beta</a>
  </li>
  
  <li class="&lt;?=get_nav_class('gamma');?&gt;">
    <a href="&lt;?=anchor('gamma');?&gt;" title="Gamma">Beta</a>
  </li>
</ul>




Theme © iAndrew 2016 - Forum software by © MyBB