Problem with adding and removing classes with jQuery when hovering over a list item.

Posted by Andrew on Stack Overflow See other posts from Stack Overflow or by Andrew
Published on 2010-05-24T00:09:19Z Indexed on 2010/05/24 0:10 UTC
Read the original article Hit count: 267

Filed under:
|

I want to add a class to a list item when I hover over it, and then remove it and add it to a different list item if a different list item is hovered over.

Here's what I tried:

jQuery -

$(document).ready(function() {
        $("#results").text("Tournaments");
        $("#Tournaments").addClass("box-active");
        $("#box ul li").hover(function() {
            var show = $(this).attr('id');
            $("#results").text(show);
            $("#box ul li").each(function() {
                $(this).removeClass("box-active");
                });
            $("#box ul li#" + show).addClass("box-active");
            });
        });

HTML -

    <div id="box">
        <ul>
            <li id="Tournaments">Tournaments</li>
            <li id="Join">Join</li>
            <li id="Forums">Forums</li>
            <li id="GameBattles">GameBattles</li>
            <li id="Practice">Practice</li>
        </ul>
        <p>Hovering over: <span id="results"></span></p>
    </div>

When I hover over an item, it changes the class, but if I hover over I different one it removes the class over the item I first hovered over, but doesn't add the class to the new item I'm hovering over. Not sure why, and any help would be appreciated.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery