Žilvinas Žilvinas - 6 months ago 19
jQuery Question

hover and click on li element change class

So I'm trying to create side navigation and I have no experience with jquerry.
What I want to do is that when hovered on any other li element than the active one the one hovered gains .active class and the initial has that class removed but when mouse leaves that element without clicking it the .active class goes again to first li element unless it is clicked. I hope you get the idea. I tried to do with .hover the hovering thing but I don't know how to revert to initial html when mouseleaves and also how to implement .click function at the same time.

         $("#nav li").hover(function() {
$("#nav li").removeClass("active");
$(this).addClass("active");            
return false;
         },
function () {
$(this).removeClass("active");
}
);       


and here is my HTML:

<nav id="nav">
<ul>
<li class="active"><a href="#slide1" title="Next Section" >About</a></li>
<li><a href="#slide2" >Works</a></li>
<li><a href="#slide3" >Contact</a></li>
</ul>



Answer

You almost got it. You don't need the "return false;" in the first hover function. That will probably interfere with the execution. That is only needed on click events because you are interrupting the default link behavior which reloads the page.

You also need to add the active class to the first list item again on the second function.

$("#nav li").hover(
   function() {
       $("#nav li").removeClass("active");
       $(this).addClass("active");                   
    }, 
   function () {
      $(this).removeClass("active");
      $("#nav li").first().addClass("active");  
   }
);