Keith
Keith

Reputation: 4137

Getting left nav link to stay open and active

Currently I have a left nav menu that works:

$('.navContainer li div').click(function () {
var $t = $(this);
var $next = $t.next('.navtoggle');
$('.navtoggle').not($next).slideUp('active');
$next.slideToggle(400);
});

The problem is, the links on the last level need to be highlighted based on the page that is on and for the nav to stay open. The script above, once clicked, will load the corresponding page and close the navigation. I have tried using the cookies and couldn't get it to work. I've tried using document ready, and it works until the page reloads and it just resets. So I am kinda stuck. I've tried:

$(document).ready(function () {
$('.navContainer .navtoggle li a').click(function (e) {
    $(e.target).addClass('current');
    });
});

.navContainer .navtoggle li a, is the last links to be used to keep it activated. I'm adding class 'current' since active is being used in the navigation. This will change the link color and thats it. I've also tried a:target and a:active, but everything just keeps getting reset.

Upvotes: 0

Views: 236

Answers (1)

Keith
Keith

Reputation: 4137

I was able to find an answer here http://www.itworld.com/article/2832973/development/setting-an-active-menu-item-based-on-the-current-url-with-jquery.html and change a couple things to make this work. Wanted to give most of the credit to that webpage but I was able to make it work using this as the base. The final code is:

$(function () {
setNavigation(); });

function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);

$(".navContainer .navtoggle li a").each(function () {
    var href = $(this).attr('href');
    if (path.substring(0, href.length) === href) {
        $(this).closest('li a').addClass('current');
        $(this).closest('.navtoggle').css('display', 'block');
    }
}); }

Upvotes: 0

Related Questions