tags:

views:

36

answers:

2

Hi all, I'm trying to write up a script that will allow me to change the css of the previous li on hover.

Here's the structure:

<ul id="mainlevel">
  <li><a href="/" class="mainlevel" id="active_menu">Home</a></li>
  <li><a href="/" class="mainlevel">About Us</a></li>
  <li><a href="/" class="mainlevel">Products</a></li>
  <li><a href="/" class="mainlevel">Projects</a></li>
  <li><a href="/" class="mainlevel">Suppliers</a></li>
</ul>

Here's what I have so far:

jQuery("#mainlevel li a").hover(function() {
    jQuery(this).prev("li a").css("background", "#f0f");
  });

But it's not working.. Any help would be appreciated :)

+3  A: 

The following seems to work:

$(document).ready(
  function() {
    $('li a').hover(
      function(){
       $(this).parent().prev('li').css('background-color','#f0f'); 
      }
      );
  }
  );

Albeit I haven't removed the background-colours when the li is no longer hovered-over.

Demo at: JS Bin.

David Thomas
@SoulieBaby, having posted this answer, it occurs to me to ask: are you sure you want to change the background of the `li`, and *not* the background of the child `a` element?
David Thomas
Oh it was to change the a, but I used what you had given me and added .find("a") to it to get it to work for me, thank you! :)
SoulieBaby
+10  A: 

Can you try this

jQuery(this).parent().prev("li").children("a").css("background", "#f0f");

I think the prev() methods works with only the siblings of the current element. that is why you have to get the parent of the current element and then get the prev element

Arun P Johny