0

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.

2 Answers 2

1

I think the answer to this question may help.

Could be something like this:

   $('#box ul li').hover( function(){
      $(this).addClass('box-active');
      $("#results").text($(this).attr('id'));
   },
   function(){
      $(this).removeClass('box-active');
      $("#results").text('');
   });

EDIT: this will remove the class when you stop hovering over the li, not sure if that's your desired functionality or not

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

Comments

0

For one, no reason to put multiple id tags in a search try:

$("li#" + show).addClass("box-active");

but even better, since you are in the li itself:

$(this).addClass('box-active');

I'm not sure if this will work, but try this:

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

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.