palAlaa
palAlaa

Reputation: 9858

change background color of li using jquery

I want to change the color of li which contains anchor when the mouse go over it, I make like this

 <ul id="SonsItemList">
     <li class="sonItem"><a id="son" href="#" >son 1</a></li>
      <li class="sonItem"><a id="son" href="#" >son 2</a></li>        
 </ul>

and jquery is

 $(document).ready(function(){
            $("a#son").hover(function(){
               $("li.sonItem").css("background-color","black");  // it make all li background => black


        });

I just want the li that the mous go over to change it's background, how can I make it ? });

Upvotes: 2

Views: 20073

Answers (4)

Naresh Kumar
Naresh Kumar

Reputation: 345

Id is unique so dont repeat, u can use in class

$(document).ready(function(){
  $(".son").hover(function(){
    $(".sonItem").css("background-color","black");
    },function(){
    $(".sonItem").css("background-color","white");
    });
});

<ul id="SonsItemList">
     <li class="sonItem"><a class="son" href="#" >son 1</a></li>
      <li class="sonItem"><a class="son" href="#" >son 2</a></li>        
</ul>

Upvotes: 0

David Lloyd Brookes
David Lloyd Brookes

Reputation: 160

If you're wanting a nice hover effect then you'll want jquery, you'll also need jquery-color.js, the code is below:

<script type="text/javascript">
    $(function () {
        $('#menu .dummyclass').mouseover(function () {
            $(this).animate({
                backgroundColor: '#FF0000'
            }, 50, function () { });
        });
    });
    $(function () {
        $('#menu .dummyclass').mouseleave(function () {
            $(this).animate({
                backgroundColor: '#000000'
            }, 600, function () { });
        });
    });
</script>

HTML Markup:

<div id="menu">
    <ul>
        <li class="dummyclass">Home</li>
        <li class="dummyclass">Fixtures</li>
        <li class="dummyclass">Results</li>
        <li class="dummyclass">Tables</li>
        <li class="dummyclass">Constitution</li>
        <li class="dummyclass" style="border-right: none;">Contact Us</li>
    </ul>
</div>

CSS:

#menu ul li .dummyclass {
    /*Dummy class to aid hovering with jQuery*/
}

Upvotes: 0

Jacob
Jacob

Reputation: 78840

You don't need any JavaScript at all. You can use CSS:

li.sonItem:hover 
{
    background-color: black;
}

Upvotes: 6

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Do it like this:

$("a[id='son']").hover(function(){
   $(this).closest("li.sonItem").css("background-color","black");  
});

NOTE: This will work ok, however you should never have more than 1 element with the same id (you can, but it's a very, very bad practice), it'd be better if you use a class, for example class="son", and your selector would be $("a.son").

Cheers

Upvotes: 2

Related Questions