0

This could be the easiest of a problem, but sometimes my dumbness knows no bounds.

I am trying to create a simple navigation menu. On clicking a link in the navigation menu, it should turn into some different layout and stay like this. I am using this code of jquery,

$(function()
{

    $(".top a").click(function()
    {
        $(this).parent().addClass('active').siblings().removeClass('active');
    };

});

and here is the menu,

<ul class="top">

<li><a href="http://example.com/index.php" class="home"></a></li>

<li><a href="http://example.com/page.php?id=1" class="charter"></a></li>

<li><a href="http://example.com/about_us.php" class="about"></a></li>

<li><a href="http://example.com/policy.php" class="policy"></a></li>

<li><a href="http://example.com/page.php?id=4" class="code"></a></li>

<li><a href="http://example.com/humanitarian.php" class="human"></a></li>

</ul>

I assign class active to li tag whenever someone clicks on any link. But the class is lost on page load. Can someone suggest me how to keep the active class there and keep the link active after the page load. There seems to be something i am missing.

Thanks.

1 Answer 1

1

JavaScript changes to the page do not persist from page to page. Instead you could try something like this:

$(function () {
    $('.top a').each(function () {
        if (this.href == window.location.href) {
            $(this).addClass('active');
            return false;
        }
    });
});

The above code will go through your navigation and add active to the first anchor matching the window's location.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.