Reputation: 688
I currently working on the menu system for this site.
I have the following code, which is working fine:
$('#menu .container ul li:not(:first-child)').fadeOut()
$('#menu .container ul li:first-child').click(function() {
$(this).siblings().fadeToggle();
})
I'm just hiding all the menu items to clean up the navigation a bit. What I now want to do is have the browser detect which section you're currently viewing (ie if you're looking at Magda under Latest Work) and automatically show that section. I'm not quite sure how to go about this. Maybe detect the URL, then find the URL in #menu .container
, and .show()
all of its siblings when it loads? Can anyone help on this one?
Upvotes: 0
Views: 2823
Reputation:
I see you've got a body class on section-n on each page. If you can apply a class to the ul of each parent menu item you'll be able to show or hide the sub-menu using
.menuparent ul { display: none; }
.bodyclass .menuparent ul { display: block; }
--edit--
Just seen that it's not coded in this way:
<ul>
<li class="menuparent">menu parent
<ul>
<li>menu sub 1</li>
<li>menu sub 2</li>
</ul>
</li>
</ul>
Which would be required for my answer to work. Probably a better way to code it up if you can as it's a parent-child menu system.
Upvotes: 1
Reputation: 7715
$("#menu a").each(function() {
if($(this).attr('href') == window.location.href) {
//Show the menu.
}
});
You'll have to fill in the bit that actually shows the menu, though. Let me know if you need help with that as well.
I tested it briefly in the Chrome Javascript console and it seemed to find the correct element. Be sure to test it across multiple browsers, though. I think this also relies on the href
element in each link being a "full" URL including the http://
and the domain name. If they are relative links (e.g. /home
) you'll want to use window.location.pathname
instead of window.location.href
.
Upvotes: 3
Reputation: 17752
You can add a certain class for the element with PHP, and then find the element with jQuery and show it.
For example:
<ul>
<li class="<?=($page_1 == $selected_page ? "active" : "");?>">Page 1</li>
<li class="<?=($page_2 == $selected_page ? "active" : "");?>">Page 2</li>
<li class="<?=($page_3 == $selected_page ? "active" : "");?>">Page 3</li>
</ul>
Then with jQuery:
$('#menu .container ul li.active:first-child').click(function() {
$(this).siblings().fadeToggle();
})
If the menu is printed with PHP automatically, it could be easily implemented.
Other approach - don't hide the selected menu in the first place, so it is instantly expanded :)
Upvotes: 2