0
$("#menu li").click(function () {
        $("#menu .active").removeAttr("class");
        $(this).attr("class","active");
    });

        <div id="menu">
            <ul>
                <li id="m1" class="active"><a>link 1</a></li>
                <li id="m2"><a>link 1</a></li>
                <li id="m3"><a>link 2</a></li>
                <li id="m4"><a>link 3</a></li>
                <li id="m5"><a>link 4</a></li>
                <li id="m6"><a>link 5</a></li>
                <li id="m6"><a href="">link 6</a></li>
                <li id="m7"><a href="">link 7</a></li>
                <li id="m8"><a>link 8</a></li>
            </ul>
        </div>

css:

#menu .active{
    background:white;
}

#menu .active a{
    opacity:0.5;
}

#menu a{
    color:#08042b;
    text-decoration:none;
    font-size:14px;
    text-shadow: 1px 0px 1px #6055c8;
    position:relative;

}

When i click a link the first time everything seems to be ok.. When i click for second time background-color of this li changed li font takes opacity 0.5, previous li hasn't active className but previous li text hasn't go to opacity:1 Any help?

5
  • 3
    instead of using attr for adding and removing classes user .addClass and .removeClass Commented Nov 27, 2011 at 12:04
  • i try this.. basic,you have right in this point. but don't change something Commented Nov 27, 2011 at 12:11
  • $("#menu li").click(function () { $("#menu .active").removeAttr("class").find("a").css("opacity",1); $(this).addClass("active"); }); That's works but why my original code doesn't work? Commented Nov 27, 2011 at 12:17
  • 2
    If you insist on such bad practice, use .prop instead of .attr. Commented Nov 27, 2011 at 12:19
  • @user726730: the reason jquery legends created .class was to make developers' life easier. I wonder why would you take a round path? Commented Nov 28, 2011 at 14:54

1 Answer 1

2

As it was said, using $("#menu .active").removeClass("active"); is more correct than removing the entire class attribute was you did, as you may ending losing other classes you may have, thus resulting in unexpected behavior.

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

1 Comment

why this: $("#menu .active").removeClass("active").find("a").css("opacity",1); works but this: $("#menu .active").removeClass("active"); not?? The class change in any case but only opacity change in the first code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.