I found some menu code which is very simple and works nicely from just jquery without plugins.
What I would like to do is to make it sticky so that when a new page is linked to, that page expands the menu (if necessary) down to the linked item and highlights that item as active if the current window.location matches the tag href.
I’ve been wading through Dom console looking but I figure there must be a simpler jquery solution if I’m lucky. any suggestions on how to achieve this much appreciated.
Thanks
$(document).ready(function() {
$('#menu ul').hide();
/* Note the following three lines added as working solution to original question. */
/* works for fully qualified url: i.e. http://www.mydomain.com/mypage.ext */
/* also note that addClass('current') requires .current class in your css */
var currentLink = $("a[href='" + location.href + "']");
currentLink.parents("ul:hidden").slideDown("normal");
currentLink.filter('a:first').addClass('current');
/* end of solution fix */
$('#menu li a').click(
function() {
var openMe = $(this).next();
var mySiblings = $(this).parent().siblings().find('ul');
if (openMe.is(':visible')) {
openMe.slideUp('normal');
} else {
mySiblings.slideUp('normal');
openMe.slideDown('normal');
}
});
});
menu is as follows:
<ul id="menu">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a>
<ul class="submenu">
<li><a href="#">3-1</a>
<ul>
<li><a href="#">3-1-1</a></li>
<li><a href="#">3-1-2</a></li>
<li><a href="#">3-1-3</a></li>
</ul>
</li>
<li><a href="#">3-2</a>
<ul>
<li><a href="#">3-2-1</a></li>
<li><a href="#">3-2-2</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">4</a></li>
<li><a href="#" title="">5</a>
<ul>
<li><a href="#">5-1</a></li>
<li><a href="#">5-2</a></li>
<li><a href="#">5-3</a></li>
</ul>
</li>
<li><a href="#" title="">6</a>
<ul>
<li><a href="#">6-1</a></li>
<li><a href="#">6-2</a></li>
<li><a href="#">6-3</a></li>
</ul>
</li>
<li><a href="#" title="">7</a></li>
<li><a href="#" title="">8</a>
<ul>
<li><a href="#">8-1</a></li>
<li><a href="#">8-2</a></li>
<li><a href="#">8-3</a></li>
</ul>
</li>
<li><a href="#" title="">9</a></li>
</ul>
Here’s the bullet-proof way to find links with matching urls:
If you always use app relative URLs for your hrefs (eg
href="/abc/123.htm"), you can use the attribute selector:If you always use absolute URLs for your hrefs (eg
href="http://mysite.com/abc/123.htm"), you can also use the attribute selector:But, if you use relative urls in your HTML, use the first technique using
.filter().Then, to expand the menu, find all the hidden parent
<ul>elements and slide them down. After the parents are displayed, if you want to expand the link’s submenu, issue a click on the link:Demo here
Demo code