I created an asp.net master page with a menu setup like this:
<menu id="menu">
<nav id="main_nav">
<ul id="menu-primary">
<li ><a href="./">Home</a></li>
<li><a href="staff.aspx">Staff</a></li>
<li><a href="">Sales</a></li>
<li><a href="">Support</a></li>
<li><a href="">Administration</a></li>
</ul>
</nav>
</menu>
In the master page, I wanted to change the CSS for the menu item when it is clicked. I implemented this jQuery script:
<script type="text/javascript">
jQuery(document).ready(function () {
$('ul li a').each(function () {
var text_splited = $(this).text().split(" ");
$(this).html("<span>" + text_splited.shift() + " " + text_splited.join(" ") + "</span> ");
});
// click on the first item on page load
$('#menu-primary li').eq(0).click();
$('#menu-primary li').click(function (e) {
alert('here');
// remove all active classes
$('#menu-primary li').removeClass('current-menu-item');
// add active class to clicked item
$(this).addClass('current-menu-item');
});
});
</script>
Here is the corresponding CSS:
nav#main_nav ul li.current-menu-item a,
nav#main_nav ul li a:hover {background: url("../images/menu_bg.png") no-repeat scroll 0 -149px transparent; border-bottom:1px solid #edf7ff}
nav#main_nav ul li.current-menu-item a span,
nav#main_nav ul li a:hover span{background: url("../images/menu_bg.png") no-repeat scroll 100% -118px transparent;}
The code to automatically click on the first item on page load works fine:
// click on the first item on page load $('#menu-primary li').eq(0).click();
$('#menu-primary li').click(function (e) {
// remove all active classes
alert($('#menu-primary li').html());
$('#menu-primary li').removeClass('current-menu-item');
// add active class to clicked item
$(this).addClass('current-menu-item');
return false;
});
However, the page doesn't load because the function returns false.
The alert message does appear, but the CSS is not being applied to the clicked item.