Giving Active Class To Anchor Tag Instead Of List Item Of Cmenu


 <?php

$this->widget('zii.widgets.CMenu',array(

  'activeCssClass'=>'active',

  'activateParents'=>true,

  'htmlOptions'=>array('class'=>'menu'),

  'id'=>'menu',

  'encodeLabel'=>false,

  'items'=>array(

  array(

.......

..........

Using this code I get <li class="active"><a href="">Some Text</a> applied to the menu item when its page is open

I want to apply active class to the anchor tag as well. How can I do that ?

What’s your reason for needing the class on the anchor? If it’s just for styling or for javascript, you can select the anchor without needing to assign the “active” class.

I want to give color and background image to the anchor. So I guess I need to use javascript to add some class ?

No, just use CSS. If you only have one level of menus, you could do this:




li.active a

{

    /* CSS rules here */

}



If you have multiple levels, you might want to only select the anchor tag that’s the immediate descendent of the li:




li.active > a

{

    /* CSS rules here */

}



Dear Shaani

The following rule will add the active class to the anchor element.




'items'=>array(

	array('label'=>'Home', 'url'=>array('/site/index')),

	array('label'=>'List', 'url'=>'',"linkOptions"=>array('href'=>CHtml::normalizeUrl(array('post/index')),'class'=>'active')),//You can set whatever the class you want.

.............................................................



To make the link really active (whenever the user is on a particular url, the corresponding menu item is also selected).

You have to overide the CMenu::isItemActive




protected function isItemActive($item,$route)

	{

		if(isset($item['url']) && is_array($item['url']) && !strcasecmp(trim($item['url'][0],'/'),$route))

		{

			unset($item['url']['#']);

			if(count($item['url'])>1)

			{

				foreach(array_splice($item['url'],1) as $name=>$value)

				{

					if(!isset($_GET[$name]) || $_GET[$name]!=$value)

						return false;

				}

			}

			return true;

		}


		//You have to add the following thing....


		if(isset($item['linkOptions']['href']))

		    { $url=$item['linkOptions']['href'];

		      $req=Yii::app()->request->url;

		      if($url==$req)

		         return true;

		    }

		

		return false;

	}



//in your controller




$this->myMenu = array(

'id'=>'myMenu',

'items'=>array(

	array(

		'label'=>'Home',

		'url'=>array('site/index'),

		'itemOptions'=>array('class'=>'visited'),

		'linkOptions'=>array('class'=>'bar'),

	),

	array('label'=>'Sign Out', 'url'=>array('site/signout')),

),

);