d3bug3r
d3bug3r

Reputation: 2586

Jquery css selected menu issue

Hi i have a jquery for changing a menu color when selected

.selected{
    background-color: red;
}
$("#nav-container>li").click(function(){
    $(this).addClass('selected')
        .siblings()
        .removeClass('selected');
});

The HTML is as follows:

<ul id="nav-container">
    <li id="welcome">
        <a href="/" >Welcome</a>
    </li>

    <li id="find">
        <a href="/find">Find</a>
    </li>

    <li id="talk">
        <a href="/talk">Talk</a>
    </li>

    <li id="events">
        <a href="/event">Events</a>
    </li>
</ul>

The color changes take place, but when the page is at new page or page reload to new page, the color is no longer are selected. What have I not added yet? Am I missing anything here?

Upvotes: 1

Views: 188

Answers (4)

pistache
pistache

Reputation: 6203

This is normal behaviour. The Javascript context is specific to a page. If you reload the page, even if some of the HTML markup is the same, its Javascript-set attributes will be reset.

You can achieve persistent element highlighting using cookies or server-side code (sessions).

You can set a cookie like this, if you use the jquery-cookie plugin :

 $("#nav-container>li").click(function(){
        $(this).addClass('selected')
        .siblings()
        .removeClass('selected');
        $.cookie("selected", $(this).attr('id'), { path: '/' })
 });

 $(document).ready(function() {
        $("#" + $.cookie("selected")).addClass('selected')
 });

Note: didn't test this code, but it should work. Of course, the user needs to have cookies enabled to use this.

Upvotes: 0

Mouad Debbar
Mouad Debbar

Reputation: 3226

You can try this:

$(function(){
    var $ul = $("#nav-container");
    var path = window.location.pathname;
    var $a = $('a[href="'+path+'"]', $ul);
    if ( $a && $a.length ) {
        var $li = $a.parent();
        $li.addClass('selected');
    }
});

and remove the click function that you have.

Upvotes: 0

Andy
Andy

Reputation: 30135

jQuery doesn't know which one you selected after a page reload, you'll have to set the selected class via a server-side code (php) or on page load check which page you are on in jQuery and set the selected class on the element.

Upvotes: 2

Kevin Kleinjung
Kevin Kleinjung

Reputation: 81

Remember that the effect of an addClass only take effect on the Current Document. You may work with SessionID and PHP

Upvotes: 0

Related Questions